Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
14,900
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find jax implementation of this notebook here Step2: Residual block Step3: Example where number of input and output channels is the same. Step4: Example where we change the number ...
Python Code: import numpy as np import matplotlib.pyplot as plt import math from IPython import display try: import torch except ModuleNotFoundError: %pip install -qq torch import torch try: import torchvision except ModuleNotFoundError: %pip install -qq torchvision import torchvision from torch...
14,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Dijkstra's Shortest Path Algorithm The notebook Set.ipynb implements <em style="color Step1: The function call shortest_path takes a node source and a set Edges. The function shortest_path ...
Python Code: %run Set.ipynb Explanation: Dijkstra's Shortest Path Algorithm The notebook Set.ipynb implements <em style="color:blue">sets</em> as <a href="https://en.wikipedia.org/wiki/AVL_tree">AVL trees</a>. The API provided by Set offers the following API: - Set() creates an empty set. - S.isEmpty() checks whether ...
14,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Load test file Step1: Run Vivado Simulation !vivado_hls /disk0/Work/xike_hls_module/hls_proj/spk_dect/solution1/script.tcl State Machine of Each Channel Each individual channel has a finite...
Python Code: din = np.fromfile('spkDect_test_spk.bin', dtype='float32') data = np.zeros((40,8)) k = 0 for t in range(40): for ch in range(8): data[t,ch] = din[k] k+=1 fig,ax = subplots(1,2,figsize=(15,5)) ax[0].plot(data[:,:4], '-o'); ax[1].plot(data[:,4:], '-o'); Explanation: Load test file End of...
14,903
Given the following text description, write Python code to implement the functionality described below step by step Description: Migration, urban-bias and the informal sector The Harris-Todaro Model This model is an adaptation of a standard two-sector open economy specific factors model (SFM) of migration. * The two s...
Python Code: import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact from scipy.optimize import bisect,newton %matplotlib inline Tbar = 200 # Fixed specific land in ag. Kbar = 200 # Fixed specific capital in manuf Lbar = 400 # Total number of mobile workers LbarMax = 400 ...
14,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Video Codec Unit (VCU) Demo Example Step1: Run the Demo Step2: Insert file path Step3: Transcode Step4: Advanced options
Python Code: from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value...
14,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Tuples Tuples are like Lists, but they are immutable, means once we assign a value to a tuple we cannot change it or it cannot be changed. Tuple values are enclosed in (). Tuple can hold val...
Python Code: t = (1,2.0,'Three') t t[0] Explanation: Tuples Tuples are like Lists, but they are immutable, means once we assign a value to a tuple we cannot change it or it cannot be changed. Tuple values are enclosed in (). Tuple can hold values of different types. You can think of them as constant arrays. End of expl...
14,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 3 Imports Step1: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is Step2: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 3 Imports End of explanation def well2d(x, y, nx, ny, L=1.0): sine1 = np.sin(nx*np.pi*x/L) sine2 = np.sin(ny*np.pi*y/L) eq = 2/L * sine1 * sine2 return(eq) psi = well2d(np.linspace(0,1,10)...
14,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Machine Learning LA Team Submission 5 ## Lukas Mosser, Alfredo De la Fuente In this approach for solving the facies classfication problem ( https Step1: Data Pre...
Python Code: %%sh pip install pandas pip install scikit-learn pip install tpot from __future__ import print_function import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold , StratifiedKFold f...
14,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Read the pregnancy file. Step1: Select live births, then make a CDF of <tt>totalwgt_lb</tt>. Step2: Display the CD...
Python Code: %matplotlib inline import nsfg preg = nsfg.ReadFemPreg() Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Read the pregnancy file. End of explanation import thinkstats2 as ts live = preg[preg.outcome == 1] wgt_cdf = ts.Cdf(live.totalwgt_lb, label = 'weight') Explanatio...
14,909
Given the following text description, write Python code to implement the functionality described below step by step Description: functions for doing the work For a given filename, colnum and rank create the desired matrix, and possibly save it in a comma separate value format that is readable by excel, origin, etc. St...
Python Code: import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable def create_matrix(filename, colnum, rank, sep=':', savecsv=False): df = pd.read_csv(filename, sep=sep, header=None, comment='#') matrix = df.iloc[:, [colnum]].val...
14,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Occupancy data Step2: Parameter projection Because the visualizer only displays results across two parameters, we need some way of reducing the dimension to 2. Our approach Step3: ...
Python Code: ## [from examples/examples.py] from download import download_all ## The path to the test data sets FIXTURES = os.path.join(os.getcwd(), "data") ## Dataset loading mechanisms datasets = { "credit": os.path.join(FIXTURES, "credit", "credit.csv"), "concrete": os.path.join(FIXTURES, "concrete", "conc...
14,911
Given the following text description, write Python code to implement the functionality described below step by step Description: Продажи австралийского вина Известны ежемесячные продажи австралийского вина в тысячах литров с января 1980 по июль 1995, необходимо построить прогноз на следующие три года. Step1: Проверка...
Python Code: %pylab inline import pandas as pd from scipy import stats import statsmodels.api as sm import matplotlib.pyplot as plt import warnings from itertools import product def invboxcox(y,lmbda): if lmbda == 0: return(np.exp(y)) else: return(np.exp(np.log(lmbda*y+1)/lmbda)) wine = pd.read_csv('m...
14,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem 24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or...
Python Code: import itertools as it def lexicographicPermutations(): l=list(range(10)) r=[''.join(map(str,x)) for x in list(it.permutations(l))] #print(len(r)) print("Millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9: "+r[999999]) lexicographicPermutations() Explanation: Problem 24 A...
14,913
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 1 Read 2 arrays x,y containing floating point values Calculate mean of x & y Calculate variance for x $$variance(x)=sum((x-mean(x))^2)$$ Calculate covariance of x & y $$covarian...
Python Code: import tensorflow as tf with tf.name_scope("var"): with tf.name_scope("mean_x"): a=tf.constant([5.0,7.0,20.2,17.32],shape=[1,4],name='a') b=tf.constant([7.0,9.0,19.0,18.0],shape=[1,4],name='b') x=tf.reduce_mean(a) sess=tf.Session() print("mean",sess.run(x)) #mean x #mean...
14,914
Given the following text description, write Python code to implement the functionality described below step by step Description: Generating simple audio samples with music21 We'd like to synthesize simple audio samples containing a single note or a chord. The samples, however, should be parameterized by several attrib...
Python Code: import music21 from music21.chord import Chord from music21.duration import Duration from music21.instrument import Instrument from music21.note import Note, Rest from music21.stream import Stream from music21.tempo import MetronomeMark from music21.volume import Volume import os data_dir = 'data/working/e...
14,915
Given the following text description, write Python code to implement the functionality described below step by step Description: Los modelos lineales son fundamentales tanto en estadística como en el aprendizaje automático, pues muchos métodos se apoyan en la combinación lineal de variables que describen los datos. Lo...
Python Code: from sklearn import datasets boston = datasets.load_boston() Explanation: Los modelos lineales son fundamentales tanto en estadística como en el aprendizaje automático, pues muchos métodos se apoyan en la combinación lineal de variables que describen los datos. Lo más sencillo será ajustar una línea recta ...
14,916
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <img align="left" style="padding-right Step1: Motivating KDE Step2: We have previously seen that the standard count-based histogram can be created with the plt.hist...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np Explanation: <!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> This notebook contains an excerpt from the Python Data Science Handbook by Jake Vande...
14,917
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: How can I perform regression in sklearn, using SVM and a gaussian kernel?
Problem: import numpy as np import pandas as pd import sklearn X, y = load_data() assert type(X) == np.ndarray assert type(y) == np.ndarray # fit, then predict X from sklearn.svm import SVR svr_rbf = SVR(kernel='rbf') svr_rbf.fit(X, y) predict = svr_rbf.predict(X)
14,918
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="#Demo-iadftscaleproperty" data-toc-modified-id="Demo-iadftscaleproperty-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Demo iadfts...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import sys,os ia898path = os.path.abspath('../../') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia f = mpimg.imread('../data/cameraman.tif') froi = f[19:19+64,99:99+64...
14,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced features tutorial The following tutorials highlight advanced functionality and provide in-depth material on ensemble APIs. =============================== =========================...
Python Code: import numpy as np from pandas import DataFrame from sklearn.metrics import accuracy_score from sklearn.datasets import load_iris seed = 2017 np.random.seed(seed) data = load_iris() idx = np.random.permutation(150) X = data.data[idx] y = data.target[idx] Explanation: Advanced features tutorial The followin...
14,920
Given the following text description, write Python code to implement the functionality described. Description: Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome ...
Python Code: def reverse_delete(s,c): s = ''.join([char for char in s if char not in c]) return (s,s[::-1] == s)
14,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Vector Laplacian in curvilinear coordinates The vector Laplacian is $$ \nabla^2 \vec{u} = \nabla \cdot \nabla \vec{u} $$ A vector identity gives the vector Laplacian as $$ \nabla^2 \vec{u} =...
Python Code: from shenfun import * from IPython.display import Math import sympy as sp config['basisvectors'] = 'normal' #'covariant' # or r, theta, z = psi = sp.symbols('x,y,z', real=True, positive=True) rv = (r*sp.cos(theta), r*sp.sin(theta), z) N = 10 F0 = FunctionSpace(N, 'F', dtype='d') F1 = FunctionSpace(N, 'F',...
14,922
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning Curves and Bias-Variance Tradeoff In practice, much of the task of machine learning involves selecting algorithms, parameters, and sets of data to optimize the results of the method...
Python Code: %pylab inline Explanation: Learning Curves and Bias-Variance Tradeoff In practice, much of the task of machine learning involves selecting algorithms, parameters, and sets of data to optimize the results of the method. All of these things can affect the quality of the results, but it’s not always clear whi...
14,923
Given the following text description, write Python code to implement the functionality described below step by step Description: <a name="pagetop"></a> <div style="width Step1: We got a Pandas dataframe back, which is great. Sadly, Pandas does not play well with units, so we need to attach units and make some other k...
Python Code: # Create a datetime for our request - notice the times are from laregest (year) to smallest (hour) from datetime import datetime request_time = datetime(1999, 5, 3, 12) # Store the station name in a variable for flexibility and clarity station = 'OUN' # Import the Wyoming simple web service and request the...
14,924
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Step 12 Step2: Publish model to Firebase ML Step 1. Upload the private key (json file) for your service account and Initialize Firebase Admin ...
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...
14,925
Given the following text description, write Python code to implement the functionality described below step by step Description: MeshCat Animations MeshCat.jl also provides an animation interface, built on top of the three.js animation system. While it is possible to construct animation clips and tracks manually, just...
Python Code: import meshcat from meshcat.geometry import Box vis = meshcat.Visualizer() ## To open the visualizer in a new browser tab, do: # vis.open() ## To open the visualizer inside this jupyter notebook, do: # vis.jupyter_cell() vis["box1"].set_object(Box([0.1, 0.2, 0.3])) Explanation: MeshCat Animations MeshCat...
14,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Theory and Practice of Visualization Exercise 2 Imports Step1: Violations of graphical excellence and integrity Find a data-focused visualization on one of the following websites that is a ...
Python Code: from IPython.display import Image Explanation: Theory and Practice of Visualization Exercise 2 Imports End of explanation # Add your filename and uncomment the following line: Image(filename='TheoryAndPracticeEx02graph.png') Explanation: Violations of graphical excellence and integrity Find a data-focused ...
14,927
Given the following text description, write Python code to implement the functionality described below step by step Description: 9 June 2017 Wayne Nixalo This notebook started out trying to generate convolutional test features using Sequential.predict_generator, by using bcolz to save the generated features to disk, i...
Python Code: import theano import os, sys sys.path.insert(1, os.path.join('utils')) from __future__ import print_function, division path = 'data/statefarm/' import utils; reload(utils) from utils import * batch_size=16 vgg = Vgg16() model = vgg.model last_conv_idx = [i for i, l in enumerate(model.layers) if type(l) is ...
14,928
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Introduction to Spark In-memmory Computing via Python PySpark </center> Spark is an implementation of the MapReduce programming paradigm that operates on in-memory data and allows d...
Python Code: !module list Explanation: <center> Introduction to Spark In-memmory Computing via Python PySpark </center> Spark is an implementation of the MapReduce programming paradigm that operates on in-memory data and allows data reuses across multiple computations. Performance of Spark is significantly better than ...
14,929
Given the following text description, write Python code to implement the functionality described below step by step Description: Darwin's bibliography <a class="tocSkip"> <p><img src="https Step1: Data Step2: Tokenize Step3: Stemming <p>As we are analysing 20 full books, the stemming algorithm can take several minu...
Python Code: import glob import re, os from tqdm import tqdm_notebook import pickle import pandas as pd from nltk.stem import PorterStemmer from gensim import corpora from gensim.models import TfidfModel from gensim import similarities import matplotlib.pyplot as plt %matplotlib inline from scipy.cluster import hierarc...
14,930
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB Add a column to dinos that contains the decimal equivalent of the sha256 hash. Hint. Step1: LAB Sort dinos by the column sha256 -- this will be an alphabetical sort. Step2: How about ...
Python Code: dinos.assign(Decimal = dinos.sha256.apply(lambda x: int(x, base=16))) Explanation: LAB Add a column to dinos that contains the decimal equivalent of the sha256 hash. Hint. End of explanation dinos.sort_values(by='sha256').head(10) Explanation: LAB Sort dinos by the column sha256 -- this will be an alphabe...
14,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Conditional Probability Solution First we'll modify the code to have some fixed purchase probability regardless of age, say 40% Step1: Next we will compute P(E|F) for some age group, let's ...
Python Code: from numpy import random random.seed(0) totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0} purchases = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0} totalPurchases = 0 for _ in range(100000): ageDecade = random.choice([20, 30, 40, 50, 60, 70]) purchaseProbability = 0.4 totals[ageDecade] += 1 if (random.r...
14,932
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Machine Learning LA Team Submission 6 ## Lukas Mosser, Alfredo De la Fuente In this approach for solving the facies classfication problem ( https Step1: Data Pre...
Python Code: %%sh pip install pandas pip install scikit-learn pip install tpot from __future__ import print_function import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold , StratifiedKFold f...
14,933
Given the following text description, write Python code to implement the functionality described below step by step Description: S&P 500 Components Time Series Get time series of all S&P 500 components Step1: Current S&P500 symbols. See my SP500 project that generates the sp500.cvs file. Step2: Create cache director...
Python Code: from datetime import datetime import pandas as pd import pinkfish as pf # -*- encoding: utf-8 -*- %matplotlib inline Explanation: S&P 500 Components Time Series Get time series of all S&P 500 components End of explanation filename = 'sp500.csv' symbols = pd.read_csv(filename) symbols = sorted(list(symbols[...
14,934
Given the following text description, write Python code to implement the functionality described below step by step Description: Build a numpy.ndarray, an equivalent dataFrame, and a numpy.rec.array Step1: Simple Array Operation Step2: pandas.dataFrame Step3: pandas.dataFrame Step4: numpy.rec.array Step5: pandas....
Python Code: rows = 10000000 # Equivalent numpy array arr = np.random.uniform(size=rows*3).reshape(rows, 3) # The pandas dataFrame with column names df = pd.DataFrame(arr, columns=['x','y','z']) # a `numpy.recarray` rec = df.to_records() df.head() df.dtypes Explanation: Build a numpy.ndarray, an equivalent dataFrame, a...
14,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Output Containers and Layout Managers Output containers are objects that hold a collection of other objects, and displays all its contents, even when they are complex interactive objects and...
Python Code: # The defining of variable doesn't initiate output x = "some string" Explanation: Output Containers and Layout Managers Output containers are objects that hold a collection of other objects, and displays all its contents, even when they are complex interactive objects and MIME type. By default the contents...
14,936
Given the following text description, write Python code to implement the functionality described below step by step Description: 02 - Introduction to Machine Learning by Alejandro Correa Bahnsen version 0.1, Feb 2016 Part of the class Practical Machine Learning This notebook is licensed under a Creative Commons Attrib...
Python Code: # Import libraries %matplotlib inline import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set(); cmap = mpl.colors.ListedColormap(sns.color_palette("hls", 3)) # Create a random set of examples from sklearn.datasets.samples_generator import make_blobs X, Y =...
14,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom Factors When we first looked at factors, we explored the set of built-in factors. Frequently, a desired computation isn't included as a built-in factor. One of the most powerful featu...
Python Code: from quantopian.pipeline import CustomFactor import numpy Explanation: Custom Factors When we first looked at factors, we explored the set of built-in factors. Frequently, a desired computation isn't included as a built-in factor. One of the most powerful features of the Pipeline API is that it allows us t...
14,938
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization 1 Step1: Scatter plots Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot. Generate random data using np.random.randn. Style the markers (color, size...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from __future__ import print_function from IPython.html.widgets import interact, interactive, fixed from IPython.html import widgets Explanation: Visualization 1: Matplotlib Basics Exercises End of explanation randx = np.random.randn(500...
14,939
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Classifiers - support vector machines (SVMs) SVMs try to construct a hyperplane maximizing the margin between the two classes. It selects a subset of the input, called the support vec...
Python Code: from sklearn import svm import matplotlib.pyplot as plt from sklearn import datasets import numpy as np %matplotlib inline iris = datasets.load_iris() iris_X = iris.data iris_y = iris.target np.unique(iris_y) svc = svm.SVC(kernel='linear') svc.fit(iris.data, iris.target) Explanation: Linear Classifiers - s...
14,940
Given the following text description, write Python code to implement the functionality described below step by step Description: EEG forward operator with a template MRI This tutorial explains how to compute the forward operator from EEG data using the standard template MRI subject fsaverage. .. caution Step1: Load t...
Python Code: import os.path as op import numpy as np import mne from mne.datasets import eegbci from mne.datasets import fetch_fsaverage # Download fsaverage files fs_dir = fetch_fsaverage(verbose=True) subjects_dir = op.dirname(fs_dir) # The files live in: subject = 'fsaverage' trans = 'fsaverage' # MNE has a built-i...
14,941
Given the following text description, write Python code to implement the functionality described below step by step Description: quant-econ Solutions Step1: Exercise 1 This exercise asked you to validate the laws of motion for $\gamma$ and $\mu$ given in the lecture, based on the stated result about Bayesian updating...
Python Code: %matplotlib inline from __future__ import division import matplotlib.pyplot as plt import numpy as np import quantecon as qe import seaborn as sns import itertools Explanation: quant-econ Solutions: Uncertainty Traps Solutions for http://quant-econ.net/py/uncertainty_traps.html End of explanation palette =...
14,942
Given the following text description, write Python code to implement the functionality described below step by step Description: BioPandas Authors Step1: Working with mmCIF Structures in DataFrames Loading mmCIF Files There are several ways to load a mmCIF structure into a PandasMmcif object. 1 -- Loading an mmCIF fi...
Python Code: %load_ext watermark %watermark -d -u -p pandas,biopandas import pandas as pd pd.set_option('display.width', 600) pd.set_option('display.max_columns', 8) Explanation: BioPandas Authors: - Sebastian Raschka &#109;&#97;&#105;&#108;&#64;&#115;&#101;&#98;&#97;&#115;&#116;&#105;&#97;&#110;&#114;&#97;&#115;&#99;...
14,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Barotropic Model Here will will use pyqg to reproduce the results of the paper Step1: McWilliams performed freely-evolving 2D turbulence ($R_d = \infty$, $\beta =0$) experiments on a $2\pi\...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pyqg Explanation: Barotropic Model Here will will use pyqg to reproduce the results of the paper: <br /> J. C. Mcwilliams (1984). The emergence of isolated coherent vortices in turbulent flow. Journal of Fluid Mechanics, 146, pp 2...
14,944
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', 'csiro-bom', 'sandbox-1', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: CSIRO-BOM Source ID: SANDBOX-1 Topic: Ocnbgchem Sub-Topics: Trac...
14,945
Given the following text description, write Python code to implement the functionality described. Description: Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells ...
Python Code: def minPath(grid, k): n = len(grid) val = n * n + 1 for i in range(n): for j in range(n): if grid[i][j] == 1: temp = [] if i != 0: temp.append(grid[i - 1][j]) if j != 0: temp.append(...
14,946
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Chapter 22 Copyright 2017 Allen Downey License Step1: Vectors A Vector object represents a vector quantity. In the context of mechanics, vector quantities...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * Explanation: Modeling and Si...
14,947
Given the following text description, write Python code to implement the functionality described below step by step Description: Nansat Step1: Open file with Nansat Step2: Read information ABOUT the data (METADATA) Step3: Read the actual DATA Step4: Check what kind of data we have Step5: Find where the image is t...
Python Code: import os import shutil import nansat idir = os.path.join(os.path.dirname(nansat.__file__), 'tests', 'data/') Explanation: Nansat: First Steps Overview The NANSAT package contains several classes: Nansat - open and read satellite data Domain - define grid for the region of interest Figure - create...
14,948
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Selection via Validation Step1: Cross-validation Step2: We can use different splitting strategies, such as random splitting (There exists many different cross-validation strategies i...
Python Code: from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import LinearSVC from sklearn import model_selection from sklearn import metrics from sklearn.datasets import load_digits digits = load_digits() X = digits.data y = digits.target X_train, X_test, ...
14,949
Given the following text description, write Python code to implement the functionality described below step by step Description: Graphistry Tutorial Step1: Connect to Graphistry + Test Step2: Connect to TigerGraph and Test Step3: Query Tigergraph Step4: Visualize result of TigerGraph query Step5: In-Tool UI Walkt...
Python Code: TIGER_CONFIG = { 'fqdn': 'http://MY_TIGER_SERVER:9000' } Explanation: Graphistry Tutorial: Notebooks + TigerGraph via raw REST calls Connect to Graphistry, TigerGraph Load data from TigerGraph into a Pandas Dataframes Plot in Graphistry as a Graph and Hypergraph Explore in Graphistry Advanced notebooks...
14,950
Given the following text description, write Python code to implement the functionality described below step by step Description: Theory and Practice of Visualization Exercise 1 Imports Step1: Graphical excellence and integrity Find a data-focused visualization on one of the following websites that is a positive examp...
Python Code: from IPython.display import Image Explanation: Theory and Practice of Visualization Exercise 1 Imports End of explanation # Add your filename and uncomment the following line: Image(filename='TheoryAndPracticeEx01graph.png') Explanation: Graphical excellence and integrity Find a data-focused visualization ...
14,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Deploying a scikit-learn model on Verta Within Verta, a "Model" can be any arbitrary function Step1: 0.1 Verta import and setup Step2: 1. Model Training 1.1 Load training data Step3: Defi...
Python Code: from __future__ import print_function import warnings from sklearn.exceptions import ConvergenceWarning warnings.filterwarnings("ignore", category=ConvergenceWarning) warnings.filterwarnings("ignore", category=FutureWarning) import itertools import os import time import six import numpy as np import pandas...
14,952
Given the following text description, write Python code to implement the functionality described below step by step Description: python_subdict - Documentation The markdown version of this document is here. Installing You can pip-install python_subdict in your environment by typing the following code on your shell Ste...
Python Code: d = { 'a': 'A', 'b': 'B', 'c': 'C', 'd': { 'x': 'D_X', 'y': 'D_Y', 'z': { 'I': 'D_Z_I', 'II': { '1': 'D_Z_II_1', '2': 'D_Z_II_2' }, 'III': 'D_Z_III' } } } Explanation: python_...
14,953
Given the following text description, write Python code to implement the functionality described below step by step Description: Define the column names and read data from source file Step1: Quick check on the summary statistics of the data set Step2: There are only 5399 unique citations when there are 5391 judgment...
Python Code: col_names = ['index', 'name', 'citation', 'author', 'number', 'date', 'court', 'coram', 'counsel', 'catchwords'] df = pd.read_table('raw.tsv', encoding='utf-8', header=None, names=col_names, index_col=0, parse_dates=True) df.head() Explanation: Define the column names and read data from source file End of ...
14,954
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have an array of experimental values and a probability density function that supposedly describes their distribution:
Problem: import numpy as np import scipy as sp from scipy import integrate,stats def bekkers(x, a, m, d): p = a*np.exp((-1*(x**(1/3) - m)**2)/(2*d**2))*x**(-2/3) return(p) range_start = 1 range_end = 10 estimated_a, estimated_m, estimated_d = 1,1,1 sample_data = [1.5,1.6,1.8,2.1,2.2,3.3,4,6,8,9] def bekkers_cdf...
14,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial for polydisperseity in with bulk Monte Carlo simulations in the structureal-color package Copyright 2016, Vinothan N. Manoharan, Victoria Hwang, Annie Stephenson This file is part o...
Python Code: %matplotlib inline import numpy as np import time import structcol as sc import structcol.refractive_index as ri from structcol import montecarlo as mc from structcol import detector as det from structcol import phase_func_sphere as pfs import matplotlib.pyplot as plt import seaborn as sns from scipy.misc ...
14,956
Given the following text description, write Python code to implement the functionality described below step by step Description: First, you'll need some data to load up. You can download example HARPS data files (and results files) to play around with linked in the documentation. Here we'll assume that you have the da...
Python Code: data = wobble.Data('../data/51peg_e2ds.hdf5') Explanation: First, you'll need some data to load up. You can download example HARPS data files (and results files) to play around with linked in the documentation. Here we'll assume that you have the data 51peg_e2ds.hdf5 saved in the wobble/data directory. By ...
14,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 4 Problem 4-29 Step1: Description A 100-MVA, 14.4-kV 0.8-PF-lagging, Y-connected synchronous generator has a negligible armature resistanc...
Python Code: %pylab notebook Explanation: Excercises Electric Machinery Fundamentals Chapter 4 Problem 4-29 End of explanation Sbase = 100e6 # [VA] Vbase = 14.4e3 # [V] ra = 0.0 # pu xs = 1.0 # pu PF = 0.8 Explanation: Description A 100-MVA, 14.4-kV 0.8-PF-lagging, Y-connected synchronous generator has a negligible arm...
14,958
Given the following text description, write Python code to implement the functionality described below step by step Description: Explore variables one at a time Step1: MSSubClass Step2: MSSubClass is categorical, though it is coded as numeric. Combine all the 1 and 1.5 story dwelling types as 1, 2 and 2.5 story type...
Python Code: # drop ID data.drop(["Id"], axis = 1, inplace=True) data.head() Explanation: Explore variables one at a time End of explanation data["MSSubClass"].isnull().sum() sns.countplot(x="MSSubClass", data=data, palette=sns.color_palette("Blues", 1)); Explanation: MSSubClass End of explanation MSSubClass = data["MS...
14,959
Given the following text description, write Python code to implement the functionality described below step by step Description: Mixed NB gnb Step1: training MultiNB & parameter tuning cat_X => countvec Step2: X_counts로 cv했을때 alpha Step3: X_tfidf로 cv했을때 alpha Step4: Tuning & Improvement Step5: Retraining with ...
Python Code: df = pd.read_csv('../resource/final_df3.csv') sample = df.title y = df['rating(y)'].values real_X = df[['avg_rating']].values cat_X = df.text.fillna("").values Explanation: Mixed NB gnb : 'avg_rating' 피쳐 한개만 mnb : alpha는 피쳐가 달라진 관계로(콤마, 띄어쓰기 제거) 다시 cv시행 ngram_range : (1, 2) tfidf : true sub_alpha : 0.3 sco...
14,960
Given the following text description, write Python code to implement the functionality described below step by step Description: Grade Step1: 1) What books topped the Hardcover Fiction NYT best-sellers list on Mother's Day in 2009 and 2010? How about Father's Day? Step2: 2) What are all the different book categories...
Python Code: import requests Explanation: Grade: 8 / 8 All API's: http://developer.nytimes.com/ Article search API: http://developer.nytimes.com/article_search_v2.json Best-seller API: http://developer.nytimes.com/books_api.json#/Documentation Test/build queries: http://developer.nytimes.com/ Tip: Remember to include y...
14,961
Given the following text description, write Python code to implement the functionality described below step by step Description: Writing your own optimization loop In this example, we will use the pyswarms.backend module to write our own optimization loop. We will try to recreate the Global best PSO using the native b...
Python Code: # Import modules import numpy as np # Import sphere function as objective function from pyswarms.utils.functions.single_obj import sphere as f # Import backend modules import pyswarms.backend as P from pyswarms.backend.topology import Star # Some more magic so that the notebook will reload external python ...
14,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. Step2: Built-in Constraints There are a number of built-in constraints that can be applied to our syst...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Advanced: Built-In Constraints 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 n...
14,963
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Let's say I have a 1d numpy positive integer array like this:
Problem: import numpy as np a = np.array([1, 0, 3]) b = np.zeros((a.size, a.max()+1)) b[np.arange(a.size), a]=1
14,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Hosts Hosts are identified in the HSC overlap check notebook. For DR1 they are (in "300 kpc" circles) Step2: Generate queries These queries are meant for the HSC casjobs at https Step3: A...
Python Code: import hosts hostobjs = hosts.get_saga_hosts_from_google() hosts.use_base_catalogs(hostobjs) hschosts = tuple([h for h in hostobjs if h.name in ('Alice', 'Othello', 'Dune')]) assert len(hschosts) == 3 hschosts for h in hschosts: h.hscfn = os.path.join('catalogs', 'hsc_pdr1_{}.csv.gz'.format(h.name)) Ex...
14,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Selection of secondary sampling units (SSUs) <a name="section2"></a> To select the second stage sample, we need the second stage frame which is the list of all the households in the 10 selec...
Python Code: %%capture %run psu_selection.ipynb Explanation: Selection of secondary sampling units (SSUs) <a name="section2"></a> To select the second stage sample, we need the second stage frame which is the list of all the households in the 10 selected clusters (psus). DHS, PHIA, MICS and other large scale surveys vi...
14,966
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
14,967
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifa...
14,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Timeseries with pandas Working with time-series data is an important part of data analysis. Starting with v0.8, the pandas library has included a rich API for time-series manipulations. The ...
Python Code: from datetime import datetime, date, time import sys sys.version import pandas as pd from pandas import Series, DataFrame, Panel pd.__version__ import numpy as np np.__version__ import matplotlib.pyplot as plt import matplotlib as mpl mpl.rc('figure', figsize=(10, 8)) mpl.__version__ Explanation: Timeserie...
14,969
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.soft - Tests unitaires, setup et ingéniérie logicielle On vérifie toujours qu'un code fonctionne quand on l'écrit mais cela ne veut pas dire qu'il continuera à fonctionner à l'avenir. La ...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() from pyensae.graphhelper import draw_diagram Explanation: 1A.soft - Tests unitaires, setup et ingéniérie logicielle On vérifie toujours qu'un code fonctionne quand on l'écrit mais cela ne veut pas dire qu'il continuera à fonctionner à l'avenir...
14,970
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 2 pre-class assignment Goals for today's pre-class assignment Make sure that you can get a Jupyter notebook up and running! Learn about algorithms, computer programs, and their relations...
Python Code: # The command below this comment imports the functionality that we need to display # YouTube videos in a Jupyter Notebook. You need to run this cell before you # run ANY of the YouTube videos. from IPython.display import YouTubeVideo Explanation: Day 2 pre-class assignment Goals for today's pre-class ass...
14,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Tracking an Unknown Number of Objects While SVI can be used to learn components and assignments of a mixture model, pyro.contrib.tracking provides more efficient inference algorithms to esti...
Python Code: import math import os import torch from torch.distributions import constraints from matplotlib import pyplot import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.contrib.tracking.assignment import MarginalAssignmentPersistent from pyro.distributions.util import gather from...
14,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Pysam Pysam è un package che mette a disposizione le funzionalità per manipolare file in formato SAM/BAM. Importare il modulo pysam Step1: Come leggere gli allineamenti da un file BAM Align...
Python Code: import pysam Explanation: Pysam Pysam è un package che mette a disposizione le funzionalità per manipolare file in formato SAM/BAM. Importare il modulo pysam End of explanation from pysam import AlignmentFile help(AlignmentFile) Explanation: Come leggere gli allineamenti da un file BAM AlignmentFile è la c...
14,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Title Step1: The above table shows the first 5 tuples of the dataset which contains two columns namely the roll no and text of the assignment. Step2: The dataset contains 1028 ent...
Python Code: # Importing pandas library import pandas as pd # Loding the data set df = pd.read_table('data.csv', sep=',', header=None, names=['rollNo','textData']) # Output printing out first 5 columns df.head() # from sklearn.feature_extraction import text Ex...
14,974
Given the following text description, write Python code to implement the functionality described below step by step Description: PLEASE MAKE A COPY BEFORE CHANGING Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. ...
Python Code: ## Import Packages import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns Explanation: PLEASE MAKE A COPY BEFORE CHANGING Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the L...
14,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Polarization Following Detlefs[2012] the electric field of a monochromatic plane wave can be described as $$ \begin{equation} \begin{split} \vec{E}(t,\vec{x}) =& \Re[(V_0\hat{e}_0 + V_1\hat{...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from spectrocrunch.sources import polarization Explanation: Polarization Following Detlefs[2012] the electric field of a monochromatic plane wave can be described as $$ \begin{equation} \begin{split} \vec{E}(t,\vec{x}) =& \Re[(V_0\hat{e}...
14,976
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: dog face detector using haar cascade
Python Code:: import cv2 import numpy as np dog_cascade = cv2.CascadeClassifier('dog_face_haar_cascade.xml') dog_face = dog_cascade.detectMultiScale(image) for (x, y, w, h) in dog_face: start_point, end_point = (x, y), (x+ w, y+h) cv2.rectangle(image, pt1= start_point, pt2 = end_point, color = (0, 255, 0), thickness ...
14,977
Given the following text description, write Python code to implement the functionality described below step by step Description: Why automate your work flow, and how to approach the process Questions for students to consider Step1: Questions for students Step2: Scope of Variables Global variables Global variables ar...
Python Code: # write out three variables, assign a number, string, list x = 'Asia' # String y = 1952 # an integer z = 1.5 # a floating point number cal_1 = y * z print(cal_1) # or x, y = 'Asia', 'Africa' w = x w = x + x #concatinating strings (combinging strings) print(w) h = 'Africa' list_1 = ['Asia', 'Africa', 'Eur...
14,978
Given the following text description, write Python code to implement the functionality described below step by step Description: Scan In short Mechanism to perform loops in a Theano graph Supports nested loops and reusing results from previous iterations Highly generic Implementation You've previous seen that a Thean...
Python Code: import theano import theano.tensor as T import numpy as np vector1 = T.vector('vector1') vector2 = T.vector('vector2') Explanation: Scan In short Mechanism to perform loops in a Theano graph Supports nested loops and reusing results from previous iterations Highly generic Implementation You've previous se...
14,979
Given the following text description, write Python code to implement the functionality described below step by step Description: Encoder-Decoder Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs B...
Python Code: report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drbef/encdec_noing10_200_512_04drbef.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drbef/encdec_noing10_200_512_04drbef_logs.json' import json imp...
14,980
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Selection For Machine Learning In this exercise, we will explore methods to do model selection in a machine learning context, in particular cross-validation and information criteria. A...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # comment out this line if you don't have seaborn installed import seaborn as sns sns.set_palette("colorblind") import numpy as np Explanation: Model Selection For Machine Learning In this exercise, we will explore methods to do model selection in a machin...
14,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural network hybrid recommendation system on Google Analytics data preprocessing This notebook demonstrates how to implement a hybrid recommendation system using a neural network to combin...
Python Code: %%bash conda update -y -n base -c defaults conda source activate py2env pip uninstall -y google-cloud-dataflow conda install -y pytz pip install apache-beam[gcp]==2.9.0 Explanation: Neural network hybrid recommendation system on Google Analytics data preprocessing This notebook demonstrates how to implemen...
14,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Netdata Anomaly Detection Deepdive This notebook will walk through a simplified python based implementation of the C & C++ code in netdata/netdata/ml/ used to power the anomaly detect...
Python Code: # uncomment the line below (when running in google colab) to install the netdata-pandas library, comment it again when done. #!pip install netdata-pandas from datetime import datetime, timedelta import itertools import random import pandas as pd import numpy as np import matplotlib.pyplot as plt import sea...
14,983
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Step1: Table 3 - Photometry Step2: Drop source 12 because it was shown to be a galaxy. Step3: %%bash mkdir ../data/Allers2006 Step4: Bonus
Python Code: %pylab inline import seaborn as sns import warnings warnings.filterwarnings("ignore") import pandas as pd Explanation: ApJdataFrames: Allers2006 Title: Young, Low-Mass Brown Dwarfs with Mid-Infrared Excesses Authors: AKCJ Data is from this paper: http://iopscience.iop.org/0004-637X/644/1/364/ End of explan...
14,984
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstration of SHyFT API implementation of Kalman Filtering on gridded data This notebook gives an example of Met.no data post-processing to correct temperature forecasts based on comparis...
Python Code: # first you should import the third-party python modules which you'll use later on # the first line enables that figures are shown inline, directly in the notebook %pylab inline import os from os import path import sys from matplotlib import pyplot as plt # once the shyft_path is set correctly, you should ...
14,985
Given the following text description, write Python code to implement the functionality described below step by step Description: 3.1 Problem description Try to build a classifier for the MNIST dataset that achieves over 97% accuracy on the test set. Hint Step1: Split test and training data Step2: 3.2 Training a Rand...
Python Code: from scipy.io import loadmat mnist = loadmat('./datasets/mnist-original.mat') mnist X, y = mnist['data'], mnist['label'] X = X.T X.shape y = y.T y.shape type(y) %matplotlib inline import matplotlib import matplotlib.pyplot as plt Explanation: 3.1 Problem description Try to build a classifier for the MNIST ...
14,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Sample Notebook for exploring gnomAD in BigQuery This notebook contains sample queries to explore the gnomAD dataset which is hosted through the Google Cloud Public Datasets Program. Setup a...
Python Code: # Import libraries import numpy as np import os # Imports for using and authenticating BigQuery from google.colab import auth Explanation: Sample Notebook for exploring gnomAD in BigQuery This notebook contains sample queries to explore the gnomAD dataset which is hosted through the Google Cloud Public Dat...
14,987
Given the following text description, write Python code to implement the functionality described below step by step Description: GCE Lab 4 - Dwarf Galaxy - Chemical Evolution Trend In this notebook, you will tune model parameters to fit the chemical evolution trend derived from stellar spectroscopy, for the dwarf sphe...
Python Code: # Import standard Python packages import matplotlib import matplotlib.pyplot as plt import numpy as np # One-zone galactic chemical evolution code import NuPyCEE.omega as omega # Stellar abundances plotting code import NuPyCEE.stellab as stellab # Matplotlib option %matplotlib inline Explanation: GCE Lab 4...
14,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Citation-https Step1: conda install numpy Step2: Download the RetinaNet model file that will be used for object detection via this link https
Python Code: ! pip install tensorflow ! pip install --upgrade pip Explanation: Citation-https://towardsdatascience.com/object-detection-with-10-lines-of-code-d6cb4d86f606 End of explanation ! pip install numpy -I import numpy.core.multiarray !pip install spacy ! pip install scipy ! pip install opencv-python ! pip insta...
14,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 1, figures 3 and 4 This notebook will show you how to produce figures 1.3 and 1.4 after the predictive modeling is completed. The predictive modeling itself, unfortunately, doesn't f...
Python Code: import pandas as pd import numpy as np from matplotlib import pyplot as plt %matplotlib inline import random accuracy_df = pd.read_csv('../modeloutput/finalbiopredicts.csv') accuracy_df.head() # I "jitter" results horizontally because we often have multiple results with the same x and y coordinates. def ji...
14,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Exam question solution Juan Valdez can earn u = 10 as a farm worker. Alternatively, if he can raise a lump-sum of I=60, he can start a risky coffee-growing project. Juan is risk-neu...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from ipywidgets import interact, fixed def E(xs,xf,p): Expectation operator return p*xs + (1-p)*xf Explanation: Exam question solution Juan Valdez can earn u = 10 as a farm worker. Alternatively, if he can raise a lump-sum of ...
14,991
Given the following text description, write Python code to implement the functionality described below step by step Description: Writing an algorithm (using pure scientific Python) In this notebook, we show how to write an algorithm for the NeuroFinder challenge using pure scientific Python. Elsewhere in the challenge...
Python Code: bucket = "s3n://neuro.datasets/" path = "challenges/neurofinder/01.00/" images = tsc.loadImages(bucket + path + 'images', startIdx=0, stopIdx=100) Explanation: Writing an algorithm (using pure scientific Python) In this notebook, we show how to write an algorithm for the NeuroFinder challenge using pure sc...
14,992
Given the following text description, write Python code to implement the functionality described below step by step Description: Poynting Vector of Half-Wave Antenna PROGRAM Step1: In this problem, I plot the magnitude of the time averaged Poynting vector for a half-wave antenna. The antenna is oriented vertically in...
Python Code: import numpy as np import matplotlib.pylab as plt Explanation: Poynting Vector of Half-Wave Antenna PROGRAM: Poynting vector of half-wave antenna CREATED: 5/30/2018 Import packages. End of explanation #Define constants - permeability of free space, speed of light, current amplitude. u_0 = 1.26 * 10**(-6) c...
14,993
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and resampling data This tutorial covers filtering and resampling, and gives examples of how filtering can be used for artifact repair. Step1: Background on filtering A filter...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) ...
14,994
Given the following text description, write Python code to implement the functionality described below step by step Description: Alignment report Step1: Read distribution by MQ Step2: Read distribution by alignment fate Step3: Mapped rate and Alignment accuracy parametrized by MQ
Python Code: # From SO: https://stackoverflow.com/a/28073228/2512851 from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form acti...
14,995
Given the following text description, write Python code to implement the functionality described below step by step Description: Ciência dos Dados - PROJETO 1 Gabriel Heusi Pereira Bueno de Camargo Título O comportamento da segurança alimentar no território brasileiro. Introdução A diversidade do território brasileiro...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import os from numpy import zeros_like print('Esperamos trabalhar no diretório') print(os.getcwd()) base = pd.read_csv('DOM2013.csv',sep=',') base9 = pd.read_csv('DOM2009.csv',sep=',') Explanation: Ciência dos Dados -...
14,996
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth for Sparse Multiple Choice Tasks Step1: Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this...
Python Code: import pandas as pd test_data = pd.read_csv("../data/event-text-sparse-multiple-choice.csv") test_data.head() Explanation: CrowdTruth for Sparse Multiple Choice Tasks: Event Extraction In this tutorial, we will apply CrowdTruth metrics to a sparse multiple choice crowdsourcing task for Event Extraction fro...
14,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Running Computations in Parallel Contents Introduction Single-Variable Functions Multi-Variable Functions IPython Based Parallel Processing Step1: <a id='intro'></a> Introduction Often one ...
Python Code: import numpy as np from qutip import * Explanation: Running Computations in Parallel Contents Introduction Single-Variable Functions Multi-Variable Functions IPython Based Parallel Processing End of explanation def func1(x): return x, x**2, x**3 a, b, c = parfor(func1, range(10)) print(a) print(b) pri...
14,998
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents The one-dimensional diffusion equation Discretizing the diffusion operator in space Coding the discretized diffusion operator in numpy Discretizing the time derivati...
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 20: A peak at numerical methods for diffusion models Warning: content out of date and not maintained You really should be looking...
14,999
Given the following text description, write Python code to implement the functionality described below step by step Description: Best practices <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: This section lists some best practices for creating a circuit that performs...
Python Code: try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq import cirq print("installed cirq.") import cirq_google as cg import sympy Explanation: Best practices <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https:/...