Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
1,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Fixed $Y_i$ & Fixed $\alpha_{MLT}$ Analysis for the case that the proto-stellar (i.e., initial) helium mass fraction is fixed to a value that is linearly proportional to the heavy element ma...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt FeH_weak = np.genfromtxt('data/run09_mle_props.txt') # weak metallicity prior FeH_strong = np.genfromtxt('data/run10_mle_props.txt') # strong metallicity prior no_Teff = np.genfromtxt('data/run11_mle_props.txt') # no Teff observa...
1,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Source Step1: Source
Python Code: flowData = pd.read_csv('../TableD_01110030-eng.csv') flowData.head() # Convert place names to unicode flowData['GEO'] = flowData['GEO'].map(u) flowData['GEODEST'] = flowData['GEODEST'].map(u) flowData.head() # Remove unneeded columns dropCols = ['Geographical classification', 'Geographical class...
1,002
Given the following text description, write Python code to implement the functionality described below step by step Description: Temporal-Comorbidity Adjusted Risk of Emergency Readmission (TCARER) <font style="font-weight Step1: 1.1. Initialise General Settings Step2: Common variables Step3: <br/><br/> 2.1. Initi...
Python Code: # reload modules # Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. %load_ext autoreload %autoreload 2 # import libraries import logging import os import sys import gc import pandas as pd import numpy as np import random import statistics from datet...
1,003
Given the following text description, write Python code to implement the functionality described below step by step Description: Image features exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more detai...
Python Code: import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading ex...
1,004
Given the following text description, write Python code to implement the functionality described below step by step Description: LEARNING This notebook serves as supporting material for topics covered in Chapter 18 - Learning from Examples , Chapter 19 - Knowledge in Learning, Chapter 20 - Learning Probabilistic Model...
Python Code: from learning import * from notebook import * Explanation: LEARNING This notebook serves as supporting material for topics covered in Chapter 18 - Learning from Examples , Chapter 19 - Knowledge in Learning, Chapter 20 - Learning Probabilistic Models from the book Artificial Intelligence: A Modern Approach...
1,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Exporting Burst Data This notebook is part of a tutorial series for the FRETBursts burst analysis software. In this notebook, show a few example of how to export FRETBursts burst data to a ...
Python Code: from fretbursts import * sns = init_notebook() Explanation: Exporting Burst Data This notebook is part of a tutorial series for the FRETBursts burst analysis software. In this notebook, show a few example of how to export FRETBursts burst data to a file. <div class="alert alert-info"> Please <b>cite</b> F...
1,006
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents First section title <a id='section1'></a> 1. First section title Some text. <div class="alert alert-success"> [Back to ATM 623 notebook home](../index.ipynb) </div> ...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture N: No title About these notes: This document uses the interactive Jupyter notebook format. The notes can be accessed in several d...
1,007
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: In this notebook, we will use a multi-layer perceptron to develop time series forecasting models. The dataset used for the examples of this notebook is on air pollution measured by co...
Python Code: from __future__ import print_function import os import sys import pandas as pd import numpy as np %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import datetime #set current working directory os.chdir('D:/Practical Time Series') #Read the dataset into a pandas.DataFrame df = ...
1,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluating Machine Learning Algorithms - Extended Examples Preparations Download Anaconda with Python 3.6 to install a nearly complete Python enviroment for data science projects Install Ker...
Python Code: # The %... is an iPython thing, and is not part of the Python language. # In this case we're just telling the plotting library to draw things on # the notebook, instead of on a separate window. %matplotlib inline # the import statements load differnt Python packages that we need for the tutorial # See all ...
1,009
Given the following text description, write Python code to implement the functionality described below step by step Description: 11 Dimensionality Reduction 11.1 Eigenvalues and Eigenvectors of Symmetric Matrices 11.1.1 Definitions $M e = \lambda e$, where $\lambda$ is an eigenvalue and $e$ is the corresponding eigenv...
Python Code: plt.imshow(plt.imread('./res/fig11_2.png')) Explanation: 11 Dimensionality Reduction 11.1 Eigenvalues and Eigenvectors of Symmetric Matrices 11.1.1 Definitions $M e = \lambda e$, where $\lambda$ is an eigenvalue and $e$ is the corresponding eigenvector. to make the eigenvector unique, we require that: ever...
1,010
Given the following text description, write Python code to implement the functionality described below step by step Description: How many movies are listed in the titles dataframe? Step1: 212811 What are the earliest two films listed in the titles dataframe? Step2: Reproduction of the Corbett and Fitzimmons Fight, M...
Python Code: titles.count() Explanation: How many movies are listed in the titles dataframe? End of explanation titles.sort('year').head() Explanation: 212811 What are the earliest two films listed in the titles dataframe? End of explanation t = titles t[t.title == 'Hamlet'].count() Explanation: Reproduction of the Cor...
1,011
Given the following text description, write Python code to implement the functionality described below step by step Description: We will use matplotlib.pyplot for plotting and scipy's netcdf package for reading the model output. The %pylab inline causes figures to appear in the page and conveniently alias pyplot to pl...
Python Code: %pylab inline import scipy.io.netcdf Explanation: We will use matplotlib.pyplot for plotting and scipy's netcdf package for reading the model output. The %pylab inline causes figures to appear in the page and conveniently alias pyplot to plt (which is becoming a widely used alias). This analysis assumes yo...
1,012
Given the following text description, write Python code to implement the functionality described below step by step Description: Relationship between common similarity metrics Reference Step1: Inner product Step2: Covariance Average centered inner product Step3: Cosine Similarity Normalized (L2) inner product Step4...
Python Code: # Import some stuff import numpy as np import pandas as pd import scipy.spatial.distance as spd from pymer4.simulate import easy_multivariate_normal from pymer4.models import Lm import matplotlib.pyplot as plt % matplotlib inline # Prep some data X = easy_multivariate_normal(50,2,corrs=.2) a, b = X[:,0], ...
1,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Easy unsupervised learning With python, scikit-learn, and handwritten digits Loading the digits dataset It's a dataset that contains around 1700 images (8x8 pixels) of handwritten digits. Re...
Python Code: from sklearn.datasets import load_digits digits_dataset = load_digits() print(digits_dataset.DESCR) digits = digits_dataset['images'] n_digits = digits.shape[0] # how many images are there? Explanation: Easy unsupervised learning With python, scikit-learn, and handwritten digits Loading the digits dataset...
1,014
Given the following text description, write Python code to implement the functionality described below step by step Description: which artist has the most songs listed? how many billboard hits did the rolling stones have? vs the beatles? how many songs total? how many years? how many song lyrics have the word 'love'? ...
Python Code: import matplotlib.pyplot as plt %matplotlib inline #Which artist has the most songs listed? print(df['Artist'].value_counts()[:1]) #How many hits did the Stones have? len(df[df['Artist'] == 'the rolling stones']) #How many did The Beatles have? len(df[df['Artist'] == 'the beatles']) #How many songs are the...
1,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Foodnet - Spanish cuisine analysis Author Step1: Graph building Step2: Graph analytics Step3: Visualitzations
Python Code: #imports import networkx as nx import pandas as pd from itertools import combinations import matplotlib.pyplot as plt from matplotlib import pylab import sys from itertools import combinations import operator from operator import itemgetter from scipy import integrate # Exploring data recipes_df = pd.rea...
1,016
Given the following text description, write Python code to implement the functionality described below step by step Description: The goal is to see how we can read the data contained in a netCDF file. Several possibilities will be examined. Reading a local file Let's assume we have downlowded a file from CMEMS. We def...
Python Code: datafile = "~/CMEMS_INSTAC/INSITU_MED_NRT_OBSERVATIONS_013_035/history/mooring/IR_TS_MO_61198.nc" import os datafile = os.path.expanduser(datafile) Explanation: The goal is to see how we can read the data contained in a netCDF file. Several possibilities will be examined. Reading a local file Let's assume ...
1,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Data from http Step1: We can list the columns in the dataset Step2: Let's look at a sorted list of the 10 most frequent types of incidents Step3: Let's group the incidents by year Step4: ...
Python Code: import pandas as pd %matplotlib inline pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 1000) df = pd.read_csv('fire-incidents.csv') df.head(3) df.shape Explanation: Data from http://catalog.data.gov/dataset/baton-rouge-fire-incidents End of explanation df.columns df['DISPATCH D...
1,018
Given the following text description, write Python code to implement the functionality described below step by step Description: Version control for fun and profit Step1: A repository Step2: And this is pretty much the essence of Git! First Step3: Other settings Change how you will edit text files (it will often as...
Python Code: !ls Explanation: Version control for fun and profit: Git: the tool you didn't know you needed Sources of this material: This tutorial is adapted from "Version Control for Fun and Profit" by Fernando Perez For an excellent list of Git resources for scientists, see Fernando's Page. Fernando's original noteb...
1,019
Given the following text description, write Python code to implement the functionality described below step by step Description: Discerning Haggis 2016-ml-contest submission Author Step1: Convenience functions Step2: Load, treat and color data Step3: Condition dataset Step4: Test, train and cross-validate Up to he...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn as sns sns.set(style='whitegrid', rc={'lines.linewidth': 2.5, 'fig...
1,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Recursive Images and Fractals Recursive images One of the cool thing about graphs is they can link to themselves. The reason why this is a graph and not a quad tree (as most maps are) is to ...
Python Code: %pylab inline import sys import os sys.path.insert(0,'..') import graphmap from graphmap.graphmap_main import GraphMap from graphmap.memory_persistence import MemoryPersistence from graphmap.graph_helpers import NodeLink G = GraphMap(MemoryPersistence()) seattle_skyline_image_url = 'https://upload.wikimedi...
1,021
Given the following text description, write Python code to implement the functionality described below step by step Description: BayesianMarkovStateModel This example demonstrates the class BayesianMarkovStateModel, which uses Metropolis Markov chain Monte Carlo (MCMC) to sample over the posterior distribution of tran...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot as plt from mdtraj.utils import timing from msmbuilder.example_datasets import load_doublewell from msmbuilder.cluster import NDGrid from msmbuilder.msm import BayesianMarkovStateModel, MarkovStateModel Explanation: BayesianMarkovStateMode...
1,022
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
1,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic CNN part-of-speech tagger with Thinc This notebook shows how to implement a basic CNN for part-of-speech tagging model in Thinc (without external dependencies) and train the model on t...
Python Code: !pip install "thinc>=8.0.0a0" "ml_datasets>=0.2.0a0" "tqdm>=4.41" Explanation: Basic CNN part-of-speech tagger with Thinc This notebook shows how to implement a basic CNN for part-of-speech tagging model in Thinc (without external dependencies) and train the model on the Universal Dependencies AnCora corpu...
1,024
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- dom Step1: With $\boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}...
Python Code: %matplotlib inline # Common imports import numpy as np import pandas as pd import matplotlib.pyplot as plt from IPython.display import display import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PRO...
1,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading the Book Ratings Dataset Step1: Loading the Books Dataset Step2: Some Books don't have unique ISBN, creating a 1 Step3: Data Preparation/ Cleaning <br> Removing ratings equal to z...
Python Code: ratings = pd.read_csv('../raw-data/BX-Book-Ratings.csv', encoding='iso-8859-1', sep = ';') ratings.columns = ['user_id', 'isbn', 'book_rating'] print(ratings.dtypes) print() print(ratings.head()) print() print("Data Points :", ratings.shape[0]) Explanation: Loading the Book Ratings Dataset End of explanati...
1,026
Given the following text description, write Python code to implement the functionality described below step by step Description: ギブスサンプリングについて $p(\bf{x}|\theta) = \frac{1}{Z(\theta)} \exp(-\Phi(\bf{x}, \theta))$ $\bf{x} = \left{ x_1, x_2, x_3, \dots, x_N \right}$ についての同時確率分布 $\bf{x} = \left{ x_1, x_2, x_3, \dots, x_N...
Python Code: import numpy from matplotlib import pyplot %matplotlib inline pyplot.style.use('ggplot') a = 0.8 num_iter = 30000 cov_inv = [[ 1, -a],[-a, 1]] mu_x = numpy.array([0, 0]) cov = numpy.linalg.pinv(cov_inv) %%time # normal sampling x_1 = [] x_2 = [] for _ in range(num_iter): data = numpy.random.multivari...
1,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2 Taylor Patti 2/15/2015 Excercises Completed Exercise 5.18 (fit_pendulum_data.py) Exercise 5.22 (midpoint_vec.py) Exercise 5.23 (Lagrange_poly1.py) Exercise 5.24 (Lagrange_poly2.py...
Python Code: p1.pendulum_plotter() p1.poly_plotter() Explanation: Homework 2 Taylor Patti 2/15/2015 Excercises Completed Exercise 5.18 (fit_pendulum_data.py) Exercise 5.22 (midpoint_vec.py) Exercise 5.23 (Lagrange_poly1.py) Exercise 5.24 (Lagrange_poly2.py) Exercise 5.25 (Lagrange_poly2b.py) fit_pendulum_data Provides ...
1,028
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Jupyter notebooks The first thing we'll do, discussed later, is import all the modules we'll need. You should in general do this at the very beginning of each notebook, and ...
Python Code: # Import numerical packages import numpy as np import scipy.integrate # Import pyplot for plotting import matplotlib.pyplot as plt # Seaborn, useful for graphics import seaborn as sns # Magic function to make matplotlib inline; other style specs must come AFTER %matplotlib inline # This enables SVG graphic...
1,029
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', 'uhh', 'sandbox-1', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-1 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energy ...
1,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Пример использования библиотеки BigARTM для тематического моделирования Для Bigartm v0.8.0 Редактировал Максим Чурилин Импортируем BigARTM Step1: Первое считывание данных (преобразуем удобн...
Python Code: from matplotlib import pyplot as plt %matplotlib inline import artm Explanation: Пример использования библиотеки BigARTM для тематического моделирования Для Bigartm v0.8.0 Редактировал Максим Чурилин Импортируем BigARTM: End of explanation batch_vectorizer = artm.BatchVectorizer(data_path="school.txt", dat...
1,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 7 Lorenzo Biasi, Julius Vernie Step1: We load the variables and initilize the parameters we need Step2: We run the filter Step3: We can see a slight offset, we would expect th...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from numpy.linalg import inv %matplotlib inline Explanation: Assignment 7 Lorenzo Biasi, Julius Vernie End of explanation data = loadmat('data_files/Tut7_file1.mat') locals().update(data) data.keys() p, T = z.shape mu = np.zer...
1,032
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook explains how to add batch normalization to VGG. The code shown here is implemented in vgg_bn.py, and there is a version of vgg_ft (our fine tuning function) with batch norm ca...
Python Code: from __future__ import division, print_function %matplotlib inline from importlib import reload import utils; reload(utils) from utils import * Explanation: This notebook explains how to add batch normalization to VGG. The code shown here is implemented in vgg_bn.py, and there is a version of vgg_ft (our ...
1,033
Given the following text description, write Python code to implement the functionality described below step by step Description: This is exactly the same as the OpenMM-based alanine dipeptide example, but this one uses Gromacs! Imports Step1: Setting up the engine Now we set things up for the Gromacs simulation. Note...
Python Code: from __future__ import print_function %matplotlib inline import matplotlib.pyplot as plt import openpathsampling as paths from openpathsampling.engines import gromacs as ops_gmx import mdtraj as md import numpy as np Explanation: This is exactly the same as the OpenMM-based alanine dipeptide example, but t...
1,034
Given the following text description, write Python code to implement the functionality described below step by step Description: CAPITOLO 1.1 Step1: Iterazione nelle liste e cicli for su indice Step2: DIZIONARI Step3: Iterazione nei dizionari ATTENZIONE Step4: DYI Step5: WARNING / DANGER / EXPLOSION / ATTENZIONE!...
Python Code: # creazione l = [1,2,3,10,"a", -12.333, 1024, 768, "pippo"] # concatenazione l += ["la", "concatenazione", "della", "lista"] # aggiunta elementi in fondo l.append(32) l.append(3) print(u"la lista è {}".format(l)) l.remove(3) # rimuove la prima occorrenza print(u"la lista è {}".format(l)) i = l.index(10) ...
1,035
Given the following text description, write Python code to implement the functionality described below step by step Description: OpenStreetMap is an open project, which means it's free and everyone can use it and edit as they like. OpenStreetMap is direct competitor of Google Maps. How OpenStreetMap can compete with t...
Python Code: OSM_FILE = 'data/map.osm' Explanation: OpenStreetMap is an open project, which means it's free and everyone can use it and edit as they like. OpenStreetMap is direct competitor of Google Maps. How OpenStreetMap can compete with the giant you ask? It's depend completely on crowd sourcing. There's lot of peo...
1,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Machine Learning with scikit-learn Lab 5 Step1: As always, we need to start with some data. Let's first generate a set of outputs $y$ and predicted outputs $\hat{y}$ to illu...
Python Code: %matplotlib inline import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) Explanation: Introduction to Machine Learning with scikit-learn Lab 5: Model evaluation and selection In this lab, we will apply a few model evaluation metrics we've seen in the lecture. End of explanation fr...
1,037
Given the following text description, write Python code to implement the functionality described below step by step Description: PyMotW - IceCream <h1 align="center"> <img src="https Step1: If you have several print calls it can quickly become unclear what is being printed where. So many of us may have ended up doi...
Python Code: def foo(i): return i + 333 print(foo(123)) Explanation: PyMotW - IceCream <h1 align="center"> <img src="https://github.com/gruns/icecream/raw/master/logo.svg" width="220px" height="370px" alt="icecream"> </h1> https://github.com/gruns/icecream available via conda-forge and pypi Never use print() to d...
1,038
Given the following text description, write Python code to implement the functionality described below step by step Description: O$_2$scl library linking example for O$_2$sclpy See the O$_2$sclpy documentation at https Step1: This code dynamically links the O$_2$scl library. Environment variables can be used to speci...
Python Code: import sys print(sys.path) import o2sclpy import sys plots=True if 'pytest' in sys.modules: plots=False Explanation: O$_2$scl library linking example for O$_2$sclpy See the O$_2$sclpy documentation at https://neutronstars.utk.edu/code/o2sclpy for more information. End of explanation link=o2sclpy.linker...
1,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Process regression tutorial 2 Step1: Problem 0 Step2: Problem 1a Step3: Now you will need to tell the GP object what inputs the covariance matrix is to be evaluated at. This is d...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import george, emcee, corner from scipy.optimize import minimize Explanation: Gaussian Process regression tutorial 2: Solutions In this tutorial, we are to explore some slightly more realistic appl...
1,040
Given the following text description, write Python code to implement the functionality described below step by step Description: Get the data 2MASS => J, H K, angular resolution ~4" WISE => 3.4, 4.6, 12, and 22 μm (W1, W2, W3, W4) with an angular resolution of 6.1", 6.4", 6.5", & 12.0" GALEX imaging => Five imaging s...
Python Code: from astroquery.gaia import Gaia tables = Gaia.load_tables(only_names=True) for table in (tables): print (table.get_qualified_name()) #obj = ["3C 454.3", 343.49062, 16.14821, 1.0] obj = ["PKS J0006-0623", 1.55789, -6.39315, 1] #obj = ["M87", 187.705930, 12.391123, 1.0] #### name, ra, dec, radius of con...
1,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Photo-z Determination for SpIES High-z Candidates Notebook that actually applies the algorithms from SpIESHighzQuasarPhotoz.ipynb to the quasar candidates. Step1: Since we are running on se...
Python Code: ## Read in the Training Data and Instantiating the Photo-z Algorithm %matplotlib inline from astropy.table import Table import numpy as np import matplotlib.pyplot as plt #data = Table.read('GTR-ADM-QSO-ir-testhighz_findbw_lup_2016_starclean.fits') #JT PATH ON TRITON to training set after classification #d...
1,042
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project Step1: Data Exploration In this first section of this project, you will make a cursory investigation about the Bos...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks import matplotlib.pyplot as plt %matplotlib inline # Load the Bost...
1,043
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering analysis In this first notebook, we conduct a k-means clustering analysis on using an included MFC mask. Fortunately, Neurosynth includes a set of functions to make this rather ea...
Python Code: import seaborn as sns from nilearn import plotting as niplt from matplotlib.colors import ListedColormap import numpy as np Explanation: Clustering analysis In this first notebook, we conduct a k-means clustering analysis on using an included MFC mask. Fortunately, Neurosynth includes a set of functions to...
1,044
Given the following text description, write Python code to implement the functionality described below step by step Description: ATLeS - Descriptive Statistics This script is designed to provide a general purpose tool for producing descriptive statistics and visualizations for ATLES data. The intent is that this noteb...
Python Code: from pathlib import Path import configparser import numpy as np import pandas as pd import seaborn import matplotlib.pyplot as plt import pingouinparametrics as pp # add src/ directory to path to import ATLeS code import os import sys module_path = os.path.abspath(os.path.join('..', 'src')) if module_path ...
1,045
Given the following text description, write Python code to implement the functionality described below step by step Description: HgTe edge in proximity to an s-wave superconductor Step1: Let us define a simple real, and hence time reversal invariant lattice model that can serve as a good description to a 1D chiral ed...
Python Code: #here we define sympy symbols to be used in the analytic calculations g,mu,b,D,k=sympy.symbols('gamma mu B Delta k',real=True) Explanation: HgTe edge in proximity to an s-wave superconductor End of explanation # onsite and hopping terms U=sympy.Matrix([[-mu+b,g,0,D], [g,-mu-b,-D,0], ...
1,046
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 DeepMind Technologies Limited. Step1: Environments <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: The code below defines ...
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...
1,047
Given the following text description, write Python code to implement the functionality described below step by step Description: Issue #42 I am a new user of toytree tool, could you tell me please how can I change the position of inner nodes added custom labels. For examble I want to plot some new_added features above...
Python Code: import toytree toytree.__version__ Explanation: Issue #42 I am a new user of toytree tool, could you tell me please how can I change the position of inner nodes added custom labels. For examble I want to plot some new_added features above or below or right the branches . Could you help me with this please?...
1,048
Given the following text description, write Python code to implement the functionality described below step by step Description: LogGabor user guide Table of content What is the LogGabor package? Installing Importing the library Properties of log-Gabor filters Testing filter generation Testing on a sample image Bu...
Python Code: %load_ext autoreload %autoreload 2 from LogGabor import LogGabor parameterfile = 'https://raw.githubusercontent.com/bicv/LogGabor/master/default_param.py' lg = LogGabor(parameterfile) lg.set_size((32, 32)) Explanation: LogGabor user guide Table of content What is the LogGabor package? Installing Importin...
1,049
Given the following text description, write Python code to implement the functionality described below step by step Description: Crash Course in Supervised Learning with scikit-learn Machine learning, like all fields of study, have a broad array of naming conventions and terminology. Most of these conventions you natu...
Python Code: from __future__ import print_function %matplotlib inline from sklearn.datasets import load_digits from matplotlib import pyplot as plt import numpy as np np.random.seed(42) # for reproducibility digits = load_digits() X = digits.data y = digits.target Explanation: Crash Course in Supervised Learning with ...
1,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Double 7's (Short Term Trading Strategies that Work) 1. The Security is above its 200-day moving average or X-day ma 2. The Security closes at a 7-day low, buy. 3. If the Security closes at ...
Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf # Format price data. pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots. '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inline %matp...
1,051
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute envelope correlations in volume source space Compute envelope correlations of orthogonalized activity Step1: Here we do some things in the name of speed, such as crop (which will hu...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Sheraz Khan <sheraz@khansheraz.com> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import mne from mne.beamformer import make_lcmv, apply_lcmv_epochs from mne.connectivity import envelope_corr...
1,052
Given the following text description, write Python code to implement the functionality described below step by step Description: Limpieza de dataset de la Encuesta Intercensal 2015 - Modulo Movilidad Cotidiana 1 . Introduccion Para la construcción de indicadores de la Plataforma de Conocimiento de Ciudades Sustentable...
Python Code: # Librerias utilizadas import pandas as pd import sys import urllib import os import numpy as np # Configuracion del sistema print('Python {} on {}'.format(sys.version, sys.platform)) print('Pandas version: {}'.format(pd.__version__)) import platform; print('Running on {} {}'.format(platform.system(), plat...
1,053
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: We show some very basic plots with matplotlib. Step2: Simplest line chart. Step3: Scatter plot. Step4: In the process of learning data visualization we will try to ...
Python Code: import matplotlib.pyplot as plt Explanation: <a href="https://colab.research.google.com/github/subarnop/AMachineLearningWalkThrough/blob/master/learning_to_plot.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Data visualization is a very...
1,054
Given the following text description, write Python code to implement the functionality described below step by step Description: QC Configuration Objective Step1: load_cfg(), just for demonstration Here we will import the load_cfg() function to illustrate different procedures. This is typically not necessary since Pr...
Python Code: # A different version of CoTeDe might give slightly different outputs. # Please let me know if you see something that I should update. import cotede print("CoTeDe version: {}".format(cotede.__version__)) Explanation: QC Configuration Objective: Show different ways to configure a quality control (QC) proced...
1,055
Given the following text description, write Python code to implement the functionality described below step by step Description: vn.past.demo - Welcome! 1. Preface past 是一个从属于vn.trader的市场历史数据解决方案模块。主要功能为: 从datayes(通联数据)等web数据源高效地爬取、更新历史数据。 基于MongoDB的数据库管理、快速查询,各种输出格式的转换。 基于Matplotlib快速绘制K线图等可视化对象。 主要依赖:pymongo,pandas,...
Python Code: # init.py from base import * if __name__ == '__main__': ds = DataGenerator() ds.download() Explanation: vn.past.demo - Welcome! 1. Preface past 是一个从属于vn.trader的市场历史数据解决方案模块。主要功能为: 从datayes(通联数据)等web数据源高效地爬取、更新历史数据。 基于MongoDB的数据库管理、快速查询,各种输出格式的转换。 基于Matplotlib快速绘制K线图等可视化对象。 主要依赖:pymongo,pandas,reque...
1,056
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Python and Julia This is a bruteforce attempt at solving Project Euler problem 14 with Python. The implementation is such that it is one-to-one with corresponding Julia code. Step1...
Python Code: # Collatz def collatz_chain(n): 'Compute the Collatz chain for number n.' k = 1 while n > 1: n = 3*n+1 if (n % 2) else n >> 1 k += 1 # print n return k def solve_euler(stop): 'Which of the number [1, stop) has the longest Collatz chain.' n, N, N_max = 1, 0, 0...
1,057
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with data 2017. Class 2 Contact Javier Garcia-Bernardo garcia@uva.nl 0. Structure Data types, structures and code II Merging and concatenating dataframes My second plots Summary Step...
Python Code: ##Some code to run at the beginning of the file, to be able to show images in the notebook ##Don't worry about this cell #Print the plots in this screen %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display import Image #Make the notebook wider from IPython.core.display ...
1,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Select, Add, Delete, Columns Step1: dictionary like operations dictionary selection with string index
Python Code: import pandas as pd import numpy as np Explanation: Select, Add, Delete, Columns End of explanation cookbook_df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]}) cookbook_df['BBB'] Explanation: dictionary like operations dictionary selection with string index End of explan...
1,059
Given the following text description, write Python code to implement the functionality described below step by step Description: 2/ Linearity Step1: Simplest linear function Step3: What about vector inputs? Step5: Linear transformations A linear transformation is function that takes vectors as inputs, and produces ...
Python Code: # setup SymPy from sympy import * init_printing() x, y, z, t = symbols('x y z t') alpha, beta = symbols('alpha beta') Explanation: 2/ Linearity End of explanation b, m = symbols('b m') def f(x): return m*x f(1) f(2) f(1+2) f(1) + f(2) expand(f(x+y)) == f(x) + f(y) Explanation: Simplest linear function...
1,060
Given the following text description, write Python code to implement the functionality described below step by step Description: Import and Preprocessing We import Yelp business data from our trimmed cleaned.csv file. For further processing, we only analyze American cities for now. Since this particular dataset has da...
Python Code: from collections import Counter from ast import literal_eval import pandas as pd import numpy as np # import and cleaning rests = pd.read_csv('cleaned.csv') rests['categories'] = rests['categories'].apply(literal_eval) # American cities only rests = rests[rests['state'].isin(['PA', 'NC', 'IL', 'AZ', 'NV', ...
1,061
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Regression By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards Part of the Quantopian Lecture Series Step1: First we'll define a f...
Python Code: # Import libraries import numpy as np from statsmodels import regression import statsmodels.api as sm import matplotlib.pyplot as plt import math Explanation: Linear Regression By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards Part of the Quantopian Lec...
1,062
Given the following text description, write Python code to implement the functionality described below step by step Description: SparkSQL Lab Step1: HiveContext, a superset of SQLContext, was recommended for most use cases. Please make sure you are using HiveContext now! Part 2 Step2: Show time Step3: (2b) Read fro...
Python Code: from pyspark.sql import SQLContext, Row sqlContext = SQLContext(sc) sqlContext from pyspark.sql import HiveContext, Row sqlContext= HiveContext(sc) sqlContext Explanation: SparkSQL Lab: From this lab, you would write code to execute SQL query in Spark. Makes your analytic life simpler and faster. During ...
1,063
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...
1,064
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting Every region has two plotting functions, which draw the outlines of all regions Step1: We use the srex regions to illustrate the plotting Step2: Plot all regions Calling plot() on...
Python Code: import regionmask regionmask.__version__ Explanation: Plotting Every region has two plotting functions, which draw the outlines of all regions: plot: draws the region polygons on a cartopy GeoAxes (map) plot_regions: draws the the region polygons only Import regionmask and check the version: End of explana...
1,065
Given the following text description, write Python code to implement the functionality described below step by step Description: Chopsticks! A few researchers set out to determine the optimal length of chopsticks for children and adults. They came up with a measure of how effective a pair of chopsticks performed, call...
Python Code: import pandas as pd # pandas is a software library for data manipulation and analysis # We commonly use shorter nicknames for certain packages. Pandas is often abbreviated to pd. # hit shift + enter to run this cell or block of code path = r'~/Downloads/chopstick-effectiveness.csv' # Change the path to the...
1,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
1,067
Given the following text description, write Python code to implement the functionality described below step by step Description: Temporal sampling Sampling nothing Let's evolve 40 populations to mutation-drift equilibrium Step1: Take samples from population Step2: The output from this particular sampler type is a ge...
Python Code: import fwdpy as fp import numpy as np import pandas as pd nregions=[fp.Region(0,1,1)] sregions=[fp.GammaS(0,1,0.1,0.1,0.1,1.0), fp.GammaS(0,1,0.9,-0.2,9.0,0.0) ] recregions=nregions N=1000 nlist=np.array([N]*(10*N),dtype=np.uint32) mutrate_neutral=50.0/float(4*N) recrate=mutrate_neutral ...
1,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Extra 3.1 - Historical Provenance - Application 2 Step1: Labelling data Based on its trust value, we categorise the data entity into two sets Step2: Having used the trust valuue to label a...
Python Code: import pandas as pd df = pd.read_csv("collabmap/ancestor-graphs.csv", index_col='id') df.head() df.describe() Explanation: Extra 3.1 - Historical Provenance - Application 2: CollabMap Data Quality Assessing the quality of crowdsourced data in CollabMap from their provenance. In this notebook, we explore th...
1,069
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: DQN C51/Rainbow <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Hyperparameters Step3: Envi...
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...
1,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Indexing Okay guys today's lecture is indexing. What is indexing? At heart, indexing is the ability to inspect a value inside a object. So basically if we have a list, X, of 100 items and ...
Python Code: # flipping signs of numbers... a = 5 b = -5 print(-a, -b) # len function x1 = [] x2 = "12" x3 = [1,2,3] print(len(x1), len(x2), len(x3)) x = [1,2,3] print(x[100]) # <--- IndexError! 100 is waayyy out of bounds Explanation: Indexing Okay guys today's lecture is indexing. What is indexing? At heart, indexi...
1,071
Given the following text description, write Python code to implement the functionality described below step by step Description: Notes on Numpy Arrays and Panda's Series and DataFrames We need to import the numpy and pandas libraries before using them in this notebook Step1: Intro to Numpy Arrays Here create a 1-dime...
Python Code: import numpy as np import pandas as pd Explanation: Notes on Numpy Arrays and Panda's Series and DataFrames We need to import the numpy and pandas libraries before using them in this notebook End of explanation array = np.array([1,2,3,4],float) array Explanation: Intro to Numpy Arrays Here create a 1-dimen...
1,072
Given the following text description, write Python code to implement the functionality described below step by step Description: Read in the Kobe Bryant shooting data [https Step1: For now, use just the numerical datatypes. They are below as num_columns Step2: The shot_made_flag is the result (0 or 1) of the shot th...
Python Code: kobe = pd.read_csv('../data/kobe.csv') Explanation: Read in the Kobe Bryant shooting data [https://www.kaggle.com/c/kobe-bryant-shot-selection] End of explanation [(col, dtype) for col, dtype in zip(kobe.columns, kobe.dtypes) if dtype != 'object'] num_columns = [col for col, dtype in zip(kobe.columns, kobe...
1,073
Given the following text description, write Python code to implement the functionality described below step by step Description: Re-referencing the EEG signal This example shows how to load raw data and apply some EEG referencing schemes. Step1: We will now apply different EEG referencing schemes and plot the resulti...
Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import mne from mne.datasets import sample from matplotlib import pyplot as plt print(__doc__) # Setup for reading the raw data data_path = sample.data_path() raw_fna...
1,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Digital Comics Data Analysis (Python) - Marvel or DC? Introduction After having done the analysis of the website (post here and the web scraping of the data from the Comixology website (post...
Python Code: import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns comixology_df = pd.read_csv("comixology_comics_dataset_19.04.2016.csv", encoding = "ISO-8859-1") Explanation: Digital Comics Data Analy...
1,075
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) Explanation: A Simple Autoencoder We'll ...
1,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Models Exercise 1 Imports Step1: Fitting a quadratic curve For this problem we are going to work with the following model Step2: First, generate a dataset using this model using th...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Fitting Models Exercise 1 Imports End of explanation a_true = 0.5 b_true = 2.0 c_true = -4.0 dy = 2.0 x = np.linspace(-5,5,30) Explanation: Fitting a quadratic curve For this problem we are going...
1,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Stroop Task Background Information In a Stroop task, participants are presented with a list of words, with each word displayed in a color of ink. The participant’s task is to say out ...
Python Code: import math import pandas as pd import scipy.stats as st from IPython.display import Latex from IPython.display import Math from IPython.display import display %matplotlib inline path = r'./stroopdata.csv' df_stroop = pd.read_csv(path) df_stroop mu_congruent = round(df_stroop['Congruent'].mean(),4) mu_inco...
1,078
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for 'spike' in column names like 'spike...
Problem: import pandas as pd data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]} df = pd.DataFrame(data) s = 'spike' def g(df, s): spike_cols = [col for col in df.columns if s in col and col != s] return df[spike_cols] result = g(df.copy(),s)
1,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with data 2017. Class 8 Contact Javier Garcia-Bernardo garcia@uva.nl 1. Clustering 2. Data imputation 3. Dimensionality reduction Step1: 3. Dimensionality reduction Many times we wa...
Python Code: ##Some code to run at the beginning of the file, to be able to show images in the notebook ##Don't worry about this cell #Print the plots in this screen %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display import Image #Make the notebook wider from IPython.core.display ...
1,080
Given the following text description, write Python code to implement the functionality described below step by step Description: graded = 9/9 Homework assignment #3 These problem sets focus on using the Beautiful Soup library to scrape web pages. Problem Set #1 Step1: Now, in the cell below, use Beautiful Soup to wri...
Python Code: from bs4 import BeautifulSoup from urllib.request import urlopen html_str = urlopen("http://static.decontextualize.com/widgets2016.html").read() document = BeautifulSoup(html_str, "html.parser") Explanation: graded = 9/9 Homework assignment #3 These problem sets focus on using the Beautiful Soup library to...
1,081
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic MR Class Step1: Spin Velocity When an atomic species with net spin is placed in a steady magnetic field, it precesses at a frequency that is characteristic of that species and that v...
Python Code: %pylab inline import matplotlib as mpl mpl.rcParams["figure.figsize"] = (8, 6) mpl.rcParams["axes.grid"] = True from IPython.display import display from ipywidgets import interact,FloatSlider Explanation: Basic MR Class: Psych 204a Tutorial: Basic MR Duration: 90 minutes Authors: Originally writte...
1,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Send email Clint Importing all dependency Step1: User Details Function Step2: Login function In this function we call user details function and get the user name and password, Than we use ...
Python Code: # ! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr import getpass Explanation: Send email Clint Importing all dependency End of explanation def user(): # ORG_EMAIL = "@...
1,083
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimizing ORM Queries Introduction This notebook provides some background on the various extractor queries. These queries are on the Submission model which has foreign key relationships on...
Python Code: import sys import sqlalchemy as sa import sqlalchemy.orm as sa_orm import testing.postgresql from app import models from app.util import sqldebug # open a test session postgresql = testing.postgresql.Postgresql(base_dir='.test_db') db_engine = sa.create_engine(postgresql.url()) models.init_database(db_engi...
1,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding similar documents with Word2Vec and WMD Word Mover's Distance is a promising new tool in machine learning that allows us to submit a query and return the most relevant documents. For...
Python Code: from time import time start_nb = time() # Initialize logging. import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s') sentence_obama = 'Obama speaks to the media in Illinois' sentence_president = 'The president greets the press in Chicago' sentence_obama = sentence_obama.lowe...
1,085
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Keras with MNIST Import various modules that we need for this notebook. Step1: Load the MNIST dataset, flatten the images, convert the class labels, and scale the data. Step...
Python Code: %pylab inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD, RMSprop from keras.utils import np_utils from keras.regularize...
1,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Training Visualization In this part we’ll see how to create a simple but wrong model with Keras, and, gradually, how it can be improved with step-by-step debugging and understanding with Ten...
Python Code: from keras.models import Model from keras.layers import Convolution2D, BatchNormalization, MaxPooling2D, Flatten, Dense from keras.layers import Input, Dropout from keras.layers.advanced_activations import ELU from keras.regularizers import l2 from keras.optimizers import SGD import tensorflow as tf from s...
1,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
1,088
Given the following text description, write Python code to implement the functionality described below step by step Description: So, this is all about the innocent little &#10033; (star or asterisk) as a versatile syntax element in Python. Depending on the context, it fulfills quite a few different roles. Here is a pi...
Python Code: # Yes. The code makes no sense. Thanks for pointing it out. from os import * def append(*, end=linesep): def _append(function): def star_reporter(*args, **kwargs): print(*args, **kwargs, end=end) return function(*args, **kwargs) return star_reporter return _a...
1,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialisation Ecrire un jeu d'instructions permettant d'initialiser la vitesse de chacun des moteurs à 30°/s. de mettre les moteurs poppy.m1 à poppy.m6 dans les positions données par la li...
Python Code: i = 0 pos_init = [0, -90, 30, 0, 60, 0] for m in poppy.motors: m.moving_speed = 60 m.compliant = False m.goal_position = pos_init[i] i = i + 1 Explanation: Initialisation Ecrire un jeu d'instructions permettant d'initialiser la vitesse de chacun des moteurs à 30°/s. de mettre les moteurs ...
1,090
Given the following text description, write Python code to implement the functionality described below step by step Description: 2-3 Trees Step1: Ths notebook presents <a href="https Step2: The function make_string is a helper function used to shorten the implementation of __str__. - obj is the object that is to b...
Python Code: import graphviz as gv Explanation: 2-3 Trees End of explanation class TwoThreeTree: sNodeCount = 0 def __init__(self): TwoThreeTree.sNodeCount += 1 self.mID = TwoThreeTree.sNodeCount def getID(self): return self.mID def isNil(self): ret...
1,091
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-state complexes <div class="admonition note"> **Topics** Step1: As usual, we first need to import required modules and define a Model object. The creation of subunit states and subuni...
Python Code: import steps.interface from steps.model import * mdl = Model() with mdl: A0, A1, A2 = SubUnitState.Create() ASU = SubUnit.Create([A0, A1, A2]) CA = Complex.Create([ASU, ASU, ASU, ASU], statesAsSpecies=True) Explanation: Multi-state complexes <div class="admonition note"> **Topics**: C...
1,092
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <img src="http Step1: <div id='intro' /> Introduction Back to TOC In this jupyter notebook we will study the behaviour of a ABSRF (A Bad and Slow Root Finder). Notice that we h...
Python Code: import numpy as np import matplotlib.pyplot as plt import sympy as sym sym.init_printing() import bitstring as bs import pandas as pd pd.set_option("display.colheader_justify","center") pd.options.display.float_format = '{:.10f}'.format # This function shows the bits used for the sign, exponent and mantiss...
1,093
Given the following text description, write Python code to implement the functionality described below step by step Description: 가우시안 정규 분포 가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다. 정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수...
Python Code: mu = 0 std = 1 rv = sp.stats.norm(mu, std) rv Explanation: 가우시안 정규 분포 가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다. 정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수(pdf: probability density function)는 다음과 같은 수식을 가진다. $$ \m...
1,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamic factors and coincident indices Factor models generally try to find a small number of unobserved "factors" that influence a subtantial portion of the variation in a larger number of o...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt np.set_printoptions(precision=4, suppress=True, linewidth=120) from pandas.io.data import DataReader # Get the datasets from FRED start = '1979-01-01' end = '2014-12-01' indprod = DataRead...
1,095
Given the following text description, write Python code to implement the functionality described below step by step Description: 错误可视化 对于任何科学的度量,准确地计算错误几乎和准确报告数字本身一样重要,甚至更为重要。例如,假设我正在使用一些天体观测来估计哈勃常数,这是对宇宙膨胀率的局部测量。我知道,目前的文献表明该值约为71(km / s)/ Mpc,我用我的方法测得的值为74(km / s)/ Mpc。值是否一致?给定此信息,唯一正确的答案是:没有办法知道。 假设我用报告的不确定性来补充此信息:当...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np x = np.linspace(0, 10, 50) dy = 0.8 y = np.sin(x) + dy * np.random.randn(50) # yerr表示y的误差 plt.errorbar(x, y, yerr=dy, fmt='.k'); Explanation: 错误可视化 对于任何科学的度量,准确地计算错误几乎和准确报告数字本身一样重要,甚至更为重要。例如,假设我正在使用一些天体...
1,096
Given the following text description, write Python code to implement the functionality described below step by step Description: Bar plot demo This example shows you how to make a bar plot using the psyplot.project.ProjectPlotter.barplot method. Step1: The default is that all bars have the same width. You can however...
Python Code: import psyplot.project as psy %matplotlib inline %config InlineBackend.close_figures = False axes = iter(psy.multiple_subplots(2, 2, n=3)) for var in ['t2m', 'u', 'v']: psy.plot.barplot( 'demo.nc', # netCDF file storing the data name=var, # one plot for each variable y=[0, 1], ...
1,097
Given the following text description, write Python code to implement the functionality described below step by step Description: PDF Analysis Tutorial Introduction This tutorial demonstrates how to acquire a multidimensional pair distribution function (PDF) from both a flat field electron diffraction pattern and a sca...
Python Code: %matplotlib inline import hyperspy.api as hs import pyxem as pxm import numpy as np Explanation: PDF Analysis Tutorial Introduction This tutorial demonstrates how to acquire a multidimensional pair distribution function (PDF) from both a flat field electron diffraction pattern and a scanning electron diffr...
1,098
Given the following text description, write Python code to implement the functionality described below step by step Description: ClickDetector use example This algorithm detects the locations of impulsive noises (clicks and pops) on the input audio frame. It relies on LPC coefficients to inverse-filter the audio in or...
Python Code: import essentia.standard as es import numpy as np import matplotlib.pyplot as plt from IPython.display import Audio from essentia import array as esarr plt.rcParams["figure.figsize"] =(12,9) def compute(x, frame_size=1024, hop_size=512, **kwargs): clickDetector = es.ClickDetector(frameSize=frame_size,...
1,099
Given the following text description, write Python code to implement the functionality described below step by step Description: automaton.compose The (accessible part of the) composition of two transducers ($A_1$ and $A_2$). Preconditions Step1: The result of the composition has a useless state. Note that only the a...
Python Code: import vcsn ctx1 = vcsn.context("lat<lal<char(ab)>, lal<char(jk)>>, b") ctx2 = vcsn.context("lat<lal<char(jk)>, lal<char(xy)>>, b") a1 = ctx1.expression("(a|k)(a|j) + (b|k)*").automaton() a1 a2 = ctx2.expression("(k|y)(k|x)*").automaton() a2 Explanation: automaton.compose The (accessible part of the) compo...