Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,200
Given the following text description, write Python code to implement the functionality described below step by step Description: Information Flows in Causal Networks This notebook replicates some examples from Ay & Polani (2008), "Information Flows in Causal Networks" in Advances in Complex Systems Volume 11, Issue 01...
Python Code: from causalinfo import * from numpy import log2 from numpy.testing import assert_allclose # You only need this if you want to draw pretty pictures of the Networksa from nxpd import draw, nxpdParams nxpdParams['show'] = 'ipynb' w, x, y, z = make_variables("W X Y Z", 2) wdist = UniformDist(w) Explanation: In...
11,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This IPython notebook illustrates how to select the best learning based matcher. First, we need to import py_entitymatching package and other libraries as follows Step1: Then, ...
Python Code: # Import py_entitymatching package import py_entitymatching as em import os import pandas as pd # Set the seed value seed = 0 # Get the datasets directory datasets_dir = em.get_install_path() + os.sep + 'datasets' path_A = datasets_dir + os.sep + 'dblp_demo.csv' path_B = datasets_dir + os.sep + 'acm_demo....
11,202
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 Explanation: Fitting a quadratic curve For this problem we are going to work with the following model:...
11,203
Given the following text description, write Python code to implement the functionality described below step by step Description: Usuarios de Energía Eléctrica Parámetros que se obtienen desde esta fuente ID |Descripción ---| Step1: 2. Descarga de datos Step2: 3. Estandarizacion de datos de Parámetros Step3: Exporta...
Python Code: descripciones = { 'P0609': 'Usuarios Electricos' } # Librerias utilizadas import pandas as pd import sys import urllib import os import csv import zipfile # Configuracion del sistema print('Python {} on {}'.format(sys.version, sys.platform)) print('Pandas version: {}'.format(pd.__version__)) import pla...
11,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Observations Observations can be thought of as the probability of being in any given state at each time step. For this demonstration, observations are randomly initialized. In a real case, t...
Python Code: observations = np.random.random((1, 90, 2)) * 4 - 2 plot(observations[0,:,:]) grid() observations_variable = tf.Variable(observations) posterior_graph, _, _ = hmm_tf.forward_backward(tf.sigmoid(observations_variable)) # build error function sum_error_squared = tf.reduce_sum(tf.square(truth - posterior_grap...
11,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 9 Step1: In this example, we switched the ordering of the arguments between the two function calls; consequently, the ordering of the arguments inside the function were also flipped...
Python Code: def pet_names(name1, name2): print("Pet 1: {}".format(name1)) print("Pet 2: {}".format(name2)) pet1 = "King" pet2 = "Reginald" pet_names(pet1, pet2) pet_names(pet2, pet1) Explanation: Lecture 9: Functions II CSCI 1360: Foundations for Informatics and Analytics Overview and Objectives In the previou...
11,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell Step1: Basic rich display Find a Physics related image on the internet and display it in t...
Python Code: # YOUR CODE HERE from IPython.display import display, Image assert True # leave this to grade the import statements Explanation: Display Exercise 1 Imports Put any needed imports needed to display rich output the following cell: End of explanation # YOUR CODE HERE Image(url='http://www.redorbit.com/media/u...
11,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Load data Let's load our data to analyze. For this example, I'm going to use some stock market data to be able to show some clear trend changes. This data can be downloaded from FRED (https ...
Python Code: market_df = pd.read_csv('../examples/SP500.csv', index_col='DATE', parse_dates=True) market_df.head() Explanation: Load data Let's load our data to analyze. For this example, I'm going to use some stock market data to be able to show some clear trend changes. This data can be downloaded from FRED (https://...
11,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a pipeline Step1: Finding the best model
Python Code: %pylab inline import sklearn from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_digits from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA digits = load_digits() X_digits = digits.data y_digits = digits.target logistic = LogisticRegression() pca = ...
11,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Plasma comparison Step1: The example tardis_example can be downloaded here tardis_example.yml Step2: Accessing the plasma states In this example, we are accessing Si and also the unionized...
Python Code: from tardis.simulation import Simulation from tardis.io.config_reader import Configuration from IPython.display import FileLinks Explanation: Plasma comparison End of explanation config = Configuration.from_yaml('tardis_example.yml') sim = Simulation.from_config(config) Explanation: The example tardis_exam...
11,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
11,211
Given the following text description, write Python code to implement the functionality described below step by step Description: LRG Position Matching We need a sample of LRGs that span the range of redshifts and i-band magnitudes found in the OM10 catalog. The sample can be kept small by selecting in color as well as...
Python Code: %matplotlib inline import om10,os import numpy as np import matplotlib.pyplot as plt import triangle Explanation: LRG Position Matching We need a sample of LRGs that span the range of redshifts and i-band magnitudes found in the OM10 catalog. The sample can be kept small by selecting in color as well as ma...
11,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Python Packages for Science The Aeropython’s guide to the Python Galaxy! Siro Moreno Martín Alejandro Sáez Mollejo 0. Introduction Python in the Scientific environment Principal Python...
Python Code: from IPython.display import HTML HTML('<iframe src="http://conda.pydata.org/docs/_downloads/conda-cheatsheet.pdf" width="700" height="400"></iframe>') Explanation: Basic Python Packages for Science The Aeropython’s guide to the Python Galaxy! Siro Moreno Martín Alejandro Sáez Mollejo 0. Introduction Python...
11,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Assembly of system with multiple domains, variables and numerics This tutorial demonstrates how a transient problem may be solved in PorePy. We consider the advective-diffusive tracer trans...
Python Code: import numpy as np import scipy.sparse as sps import porepy as pp import data.flow_benchmark_2d_geiger_setup as setup Explanation: Assembly of system with multiple domains, variables and numerics This tutorial demonstrates how a transient problem may be solved in PorePy. We consider the advective-diffusiv...
11,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Inference Sandbox In this notebook, we'll mock up some data from the linear model, as reviewed here. Then it's your job to implement a Metropolis sampler and constrain the posterior distriub...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.stats %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 5.0) # the model parameters a = np.pi b = 1.6818 # my arbitrary constants mu_x = np.exp(1.0) # see definitions above tau_x = 1.0 s = 1.0 N = 50 # number of data points # get some...
11,215
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: Soluition Step2: Bonus
Python Code: first_commit = git_log.index[-1] first_commit today = pd.to_datetime('today') type(today) Explanation: Note: We are using the UNIX timestamp here because it's superfast to convert it to a real datatime64 data type. Cleaning up wrong timestamps _Note: 'today'is suboptimal End of explanation git_log[(git_log...
11,216
Given the following text description, write Python code to implement the functionality described below step by step Description: ============================================== Read and visualize projections (SSP and other) ============================================== This example shows how to read and visualize Sign...
Python Code: # Author: Joan Massich <mailsik@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import read_proj from mne.io import read_raw_fif from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname = data_path ...
11,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's start off with a square figure. Step1: Give it a nice wooden color http Step2: The default background color for Axes is white. Let's propagate the figure background color by making t...
Python Code: fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(1, 1, 1) plt.show() Explanation: Let's start off with a square figure. End of explanation BOARD_COLOR = '#d7be9f' fig = plt.figure(figsize=(5, 5), facecolor=BOARD_COLOR) ax = fig.add_subplot(1, 1, 1) plt.show() Explanation: Give it a nice wooden color h...
11,218
Given the following text description, write Python code to implement the functionality described below step by step Description: Dropout Dropout是一种用于深度神经网络的方法,用于避免过拟合. 在训练时,每次迭代中每层以提前设定的概率,称为keep_prob,来随机选择保留的节点,其他的节点在该次前向传播被忽略(设为0),同时在后向传播中也忽略.如下图中打叉的节点就是某次迭代中忽略的节点. 作用,应用 Dropout主要有两个作用 Step2: 用pytorch来实现,尽量做到每层保留...
Python Code: keep_prob = 0.5 do_dropout = True Explanation: Dropout Dropout是一种用于深度神经网络的方法,用于避免过拟合. 在训练时,每次迭代中每层以提前设定的概率,称为keep_prob,来随机选择保留的节点,其他的节点在该次前向传播被忽略(设为0),同时在后向传播中也忽略.如下图中打叉的节点就是某次迭代中忽略的节点. 作用,应用 Dropout主要有两个作用: dropout在训练时每个迭代中相当于减小了网络规模,有正则化的作用. dropout可以避免把过多的权重放在某个节点上,而是把权重分散给全部的节点. 在实践中,dropout在C...
11,219
Given the following text description, write Python code to implement the functionality described below step by step Description: This script shows how to use the existing code in opengrid to create a baseload electricity consumption benchmark. Step1: Script settings Step2: We create one big dataframe, the columns ar...
Python Code: import os, sys import inspect import numpy as np import datetime as dt import time import pytz import pandas as pd import pdb script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # add the path to opengrid to sys.path sys.path.append(os.path.join(script_dir, os.pardir, os....
11,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Sinusoid autoencoder trained with multiple phases Let's provide more training examples - sinusoid with various phases. Step1: The model should be able to handle noise-corrupted input signal...
Python Code: %pylab inline import keras import numpy as np import keras N = 50 # phase_step = 1 / (2 * np.pi) t = np.arange(50) phases = np.linspace(0, 1, N) * 2 * np.pi x = np.array([np.sin(2 * np.pi / N * t + phi) for phi in phases]) print(x.shape) imshow(x); plot(x[0]); plot(x[1]); plot(x[2]); from keras.models impo...
11,221
Given the following text description, write Python code to implement the functionality described below step by step Description: 1 Introduccion a IPython notebooks/ Jupyter Que es exactamente? Una libreta IPython/Jupyter es un ambiente interactivo para escribir y correr codigo de python. Es un historial completo y aut...
Python Code: print("hola bolivia") Explanation: 1 Introduccion a IPython notebooks/ Jupyter Que es exactamente? Una libreta IPython/Jupyter es un ambiente interactivo para escribir y correr codigo de python. Es un historial completo y auto-contenido de un calculo y puede ser convertido a otros formatos para compartir c...
11,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Try not to peek at the solutions when you go through the exercises. ;-) First let's make sure this notebook works well in both Python 2 and Python 3 Step1: TensorFlow basics Step2: Constru...
Python Code: from __future__ import absolute_import, division, print_function, unicode_literals Explanation: Try not to peek at the solutions when you go through the exercises. ;-) First let's make sure this notebook works well in both Python 2 and Python 3: End of explanation import tensorflow as tf tf.__version__ Exp...
11,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoregressive (AR) Models by Maxwell Margenot, Delaney Mackenzie, and Lee Tobey Lee Tobey is the founder of Hedgewise. Part of the Quantopian Lecture Series Step1: Note how this process fl...
Python Code: import numpy as np import pandas as pd from scipy import stats import statsmodels.api as sm import statsmodels.tsa as tsa import matplotlib.pyplot as plt # ensures experiment runs the same every time np.random.seed(100) # This function simluates an AR process, generating a new value based on historial valu...
11,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Github https Step3: List Comprehensions Step4: Dictionaries Python dictionaries are awesome. They are hash tables and have a lot of neat CS properties. Learn and use them well.
Python Code: # Create a [list] days = ['Monday', # multiple lines 'Tuesday', # acceptable 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', # trailing comma is fine! ] days # Simple for-loop for day in days: print(day) # Double for-loop for day in da...
11,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of indiv...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dim...
11,226
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Serving in 10 minutes! TensorFlow SERVING is Googles' recommended way to deploy TensorFlow models. Without proper computer engineering background, it can be quite intimidating, ev...
Python Code: import tensorflow as tf x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x,W) + b cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logit...
11,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Factory methods Factory methods are the primary way of creating useful geometries fast. They form an abstraction level up from knot vectors and control-points to give a cleaner simpler inter...
Python Code: import splipy as sp import numpy as np import splipy.curve_factory as curve_factory import splipy.surface_factory as surface_factory import splipy.volume_factory as volume_factory Explanation: Factory methods Factory methods are the primary way of creating useful geometries fast. They form an abstractio...
11,228
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import numpy as np import pandas as pd from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() # print(cancer.DESCR) Explanation: You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera p...
11,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization Exercise 1 Imports Step1: Hat potential The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Optimization Exercise 1 Imports End of explanation def hat(x,a,b): v = -a*(x**2) + b*(x**4) return v assert hat(0.0, 1.0, 1.0)==0.0 assert hat(0.0, 1.0, 1.0)==0.0 assert hat(1.0, 10.0, 1....
11,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Abstract Neural networking is a form of machine learning inspired by the biological function of the human brain. By giving the program known inputs and outputs of a function, the computer le...
Python Code: import numpy as np from sklearn.datasets import load_digits digits = load_digits() from IPython.html.widgets import interact %matplotlib inline import matplotlib.pyplot as plt import timeit from IPython.display import Image import NNpix as npx import timeit Explanation: Abstract Neural networking is a for...
11,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Step1: Load some data I'm going to work with the data from the combined data sets. The analysis for this data set is in analysis\Cf072115_to_Cf072215b. The one limitation here is that ...
Python Code: import os import sys import matplotlib.pyplot as plt import numpy as np import imageio import pandas as pd import seaborn as sns sns.set(style='ticks') sys.path.append('../scripts/') import bicorr as bicorr import bicorr_e as bicorr_e import bicorr_plot as bicorr_plot import bicorr_sums as bicorr_sums impo...
11,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Air-Standard Brayton Cycle Example Imports Step1: Definitions Step2: Problem Statement An ideal air-standard Brayton cycle operates at steady state with compressor inlet conditions of 300....
Python Code: from thermostate import State, Q_, units from thermostate.plotting import IdealGas import numpy as np %matplotlib inline import matplotlib.pyplot as plt Explanation: Air-Standard Brayton Cycle Example Imports End of explanation substance = 'air' p_1 = Q_(1.0, 'bar') T_1 = Q_(300.0, 'K') T_3 = Q_(1700.0, 'K...
11,233
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-3', 'sandbox-3', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: TEST-INSTITUTE-3 Source ID: SANDBOX-3 Topic: Ocean Sub-Topics: Ti...
11,234
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-1', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: DWD Source ID: SANDBOX-1 Topic: Landice Sub-Topics: Glaciers, Ice. Proper...
11,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterators [GA Table] Contructing PySAL Spatial Weights Spatial Weight Matrix ...
Python Code: import Weights as WEIGHTS import os as OS inputFC = r'../data/CA_Polygons.shp' fullFC = OS.path.abspath(inputFC) fullPath, fcName = OS.path.split(fullFC) masterField = "MYID" Explanation: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterato...
11,236
Given the following text description, write Python code to implement the functionality described below step by step Description: 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, then ...
Python Code: 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_cifar10_location = '/input/cifar-10/python.tar.gz' if isfile(fl...
11,237
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow's Deep MNIST tutorial https Step1: Initiate a tf.session We're going to eventually define a graph which will represent a "dataflow computation". Before we start buiding our graph...
Python Code: #load mnist data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) Explanation: TensorFlow's Deep MNIST tutorial https://www.tensorflow.org/get_started/mnist/pros start tf.session define a model define a training loss function train usi...
11,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Import libraries Step1: Define source paths Step2: Import data Step3: Data exploration Shape, types Step4: Missing values Step5: We want to know what you look for in the opposite sex. S...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('display.max_columns', None) %matplotlib inline Explanation: Import libraries End of explanation source_path = "/Users/sandrapietrowska/Documents/Trainings/luigi/data_source/" Explanation: Define source paths End of explan...
11,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Example to_hdf calls Initialize the simulation with the tardis_example.yml configuration file. Step1: Run the simulation while storing all its iterations to an HDF file. The first parameter...
Python Code: from tardis.io.config_reader import Configuration from tardis.model import Radial1DModel from tardis.simulation import Simulation # Must have the tardis_example folder in the working directory. config_fname = 'tardis_example/tardis_example.yml' tardis_config = Configuration.from_yaml(config_fname) model = ...
11,240
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="#Preparations" data-toc-modified-id="Preparations-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Preparations</a></div><div class=...
Python Code: bigsourcefile = 'TextProcessing_2017/W0013.orig.txt' # This is the path to our file input = open(bigsourcefile, encoding='utf-8').readlines() # We use a variable 'input' for # keeping its contents. input[:10] ...
11,241
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by wdonahoe. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test The following unit test is expected to fail u...
Python Code: def group_ordered(list_in): # TODO: Implement me pass Explanation: <small><i>This notebook was prepared by wdonahoe. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Implement a function that groups identical items based on their order in the list. Constraints Test Case...
11,242
Given the following text description, write Python code to implement the functionality described below step by step Description: A Tour of SciKit-Learn + TensorFlow + SkFlow When we talk about Data Science and the Data Science Pipeline, we are typically talking about the management of data flows for a specific purpose...
Python Code: %matplotlib inline # Things we'll need later import time import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import r2_score from sklearn.metrics import classification_report from sklearn import cross_validation as cv # Load the exam...
11,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Styling New in version 0.17.1 <span style="color Step1: Here's a boring example of rendering a DataFrame, without any (visible) styles Step2: Note Step4: The row0_col2 is the identifier f...
Python Code: import matplotlib.pyplot # We have this here to trigger matplotlib's font cache stuff. # This cell is hidden from the output import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE...
11,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Data Step2: View All Rows Step3: View Rows Where Age Is Greater Than 20 And City Is San Francisco Step4: View Rows Where Age Is Greater Than 20 or City Is San Francis...
Python Code: # Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False Explanation: Title: Multiple Conditional Statements Slug: multiple_conditional_statements Summary: Multiple Conditional Statements in SQL. Date: 2017-01-16 12:00 Category: SQL Tags: Basics Authors: Chris Albon Note: This tutorial w...
11,245
Given the following text description, write Python code to implement the functionality described below step by step Description: 目录遍历 下面整理常见的目录遍历方式 Step1: os.scandir 返回可迭代的对象os.DirEntry ,可以直接判断是文件还是目录等. Step2: os.walk 可以递归遍历目录, 另外还支持遍历符号链接指向的目录. Step3: glob.glob 如果文件比较多的话可以使用glob.iglob提高性能. Step4: pathlib.Path 自从p...
Python Code: import os os.listdir('traverse-directories') Explanation: 目录遍历 下面整理常见的目录遍历方式: os.listdir os.scandir os.walk os.listdir glob.glob pathlib.Path 目录结构为: ``` traverse-directories sell.txt fuit-shop\ orange.txt apple.txt car\ small-car\ 奔驰.txt big-car\ ...
11,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Async optimization Loop Bayesian optimization is used to tune parameters for walking robots or other experiments that are not a simple (expensive) function call. Tim Head, February 2017. Ref...
Python Code: print(__doc__) import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt Explanation: Async optimization Loop Bayesian optimization is used to tune parameters for walking robots or other experiments that are not a simple (expensive) function call. Tim Head, February 2017. Reformatted by Holge...
11,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 2. Mathematical Groundwork Previous Step1: Import section specific modules
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary 2. Mathematical Groundwork Previous: 2.5 Convolution Next: 2.7 Fourier Theorems Import standard modules: End of explanation pa...
11,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports and configuration We set the path to the config.cfg file using the environment variable 'PYPMJ_CONFIG_FILE'. If you do not have a configuration file yet, please look into the Setting...
Python Code: import os os.environ['PYPMJ_CONFIG_FILE'] = '/path/to/your/config.cfg' Explanation: Imports and configuration We set the path to the config.cfg file using the environment variable 'PYPMJ_CONFIG_FILE'. If you do not have a configuration file yet, please look into the Setting up a configuration file example....
11,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 2 Imports Step2: Factorial Write a function that computes the factorial of small numbers using np.arange and np.cumprod. Step4: Write a function that computes the factorial ...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 2 Imports End of explanation def np_fact(n): Compute n! = n*(n-1)*...*1 using Numpy. if n==0: return 1 else: a=np.arange(1.0, (n+1), 1.0) b= a.cumprod(...
11,250
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Helpers Step3: Load exekall's ValueDB This notebook is meant for analysing a set of results coming from a test session executed using exekall (potentially via bisector). Since it onl...
Python Code: def collect_value(db, cls, key_path): Collect objects computed for the exekall subexpression pointed at by ``key_path``, starting from objects of type ``cls``. The path is a list of parameter names that allows locating a node in the graph of an expression. The path from z to x is ['par...
11,251
Given the following text description, write Python code to implement the functionality described below step by step Description: !!! D . R . A . F . T !!! Lightness Lightness is defined as the brightness of an area judged relative to the brightness of a similarly illuminated area that appears to be white or highly tra...
Python Code: import colour colour.utilities.filter_warnings(True, False) sorted(colour.LIGHTNESS_METHODS.keys()) Explanation: !!! D . R . A . F . T !!! Lightness Lightness is defined as the brightness of an area judged relative to the brightness of a similarly illuminated area that appears to be white or highly transmi...
11,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Fourier analysis & resonances A great benefit of being able to call rebound from within python is the ability to directly apply sophisticated analysis tools from scipy and other python libra...
Python Code: import rebound import numpy as np sim = rebound.Simulation() sim.units = ('AU', 'yr', 'Msun') sim.add("Sun") sim.add("Jupiter") sim.add("Saturn") Explanation: Fourier analysis & resonances A great benefit of being able to call rebound from within python is the ability to directly apply sophisticated analys...
11,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Occasionally, absolutely crazy ideas crop up into my noggin. Recently, I've had two take up residence almost simultaneously, both related to pynads. Haskell Type Signatures Since Pynads is, ...
Python Code: def my_func(a: int, b: str = 'hello') -> tuple: return (a, b) my_func(1, 'wut') Explanation: Occasionally, absolutely crazy ideas crop up into my noggin. Recently, I've had two take up residence almost simultaneously, both related to pynads. Haskell Type Signatures Since Pynads is, nominally, a learnin...
11,254
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="#ATENÇÃO Step1: Note que a imagem possui 174 linhas e 314 colunas, totalizando mais de 54 mil pixels. A representação do pixel é pel...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np !ls ../data f = mpimg.imread('../data/cameraman.tif') print('Tamanho de f: ', f.shape) print('Tipo do pixel:', f.dtype) print('Número total de pixels:', f.size) print('Pixels:\n', f) Explanation: Table of...
11,255
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have an array :
Problem: import numpy as np a = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) low = 1 high = 5 result = a[:, low:high]
11,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute sparse inverse solution with mixed norm Step1: Run solver with SURE criterion Step2: Plot dipole activations Step3: Plot residual Step4: Generate stc from dipoles Step5: View i...
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # # License: BSD-3-Clause import numpy as np import mne from mne.datasets import sample from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles from mne.minimum_norm import make...
11,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Wayne Nixalo - 4 Jun 2017 Codealong of Practical Deep Learning I Lesson 4 statefarm JNB. My comments are in italics. 6 Jun 2017 NOTE Step1: Setup Batches Step2: Rather than using batches, ...
Python Code: import theano import os, sys sys.path.insert(1, os.path.join('utils')) %matplotlib inline from __future__ import print_function, division path = "data/statefarm/" import utils; reload(utils) from utils import * from IPython.display import FileLink # batch_size=32 batch_size=16 Explanation: Wayne Nixalo - 4...
11,258
Given the following text description, write Python code to implement the functionality described below step by step Description: TFRecord and tf.Example Learning Objectives Understand the TFRecord format for storing data Understand the tf.Example message type Read and Write a TFRecord file Introduction In this noteboo...
Python Code: # Run the chown command to change the ownership of the repository !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # You can use any Python source file as a module by executing an import statement in some other Python source file. # The import statement combines two operations; it searche...
11,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Morph volumetric source estimate This example demonstrates how to morph an individual subject's Step1: Setup paths Step2: Compute example data. For reference see ex-inverse-volume. Load da...
Python Code: # Author: Tommy Clausner <tommy.clausner@gmail.com> # # License: BSD (3-clause) import os import nibabel as nib import mne from mne.datasets import sample, fetch_fsaverage from mne.minimum_norm import apply_inverse, read_inverse_operator from nilearn.plotting import plot_glass_brain print(__doc__) Explanat...
11,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook shows how to plot an XRD plot for the two polymorphs of CsCl ($Pm\overline{3}m$ and $Fm\overline{3}m$). You can also use matgenie.py's diffraction command to plot ...
Python Code: # Set up some imports that we will need from pymatgen import Lattice, Structure from pymatgen.analysis.diffraction.xrd import XRDCalculator from IPython.display import Image, display %matplotlib inline Explanation: Introduction This notebook shows how to plot an XRD plot for the two polymorphs of CsCl ($Pm...
11,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization in Depth With Bokeh For details on bokeh, see http Step1: Objectives Describe how to create interactive visualizations using bokeh Running example and visualization goals How ...
Python Code: from bokeh.plotting import figure, output_file, show, output_notebook, vplot import random import numpy as np import pandas as pd output_notebook() # Use so see output in the Jupyter notebook import bokeh bokeh.__version__ Explanation: Visualization in Depth With Bokeh For details on bokeh, see http://bok...
11,262
Given the following text description, write Python code to implement the functionality described below step by step Description: GRID_LRT Testbed Notebook 1. Setting up the Environment The GRID LOFAR TOOLS have several infrastructure requirements. They are as follows Step1: This should give a confirmation of that you...
Python Code: import os import GRID_LRT print(GRID_LRT.__file__) import subprocess from GRID_LRT.get_picas_credentials import picas_cred from GRID_LRT.Staging import stage_all_LTA from GRID_LRT.Staging import state_all from GRID_LRT.Staging import stager_access from GRID_LRT.Staging.srmlist import srmlist from GRID_LRT ...
11,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Deep Learning Project Step1: Step 1 Step2: Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pic...
Python Code: # Load pickled data import pickle import cv2 # for grayscale and normalize # TODO: Fill this in based on where you saved the training and testing data training_file ='traffic-signs-data/train.p' validation_file='traffic-signs-data/valid.p' testing_file = 'traffic-signs-data/test.p' with open(training_file,...
11,264
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting the cloudsat groundtrack on a modis raster This notebook is my solution to Assignment 16, satellite groundtrack assigned on Day 26 Environment requires Step1: 1. Read in the ground...
Python Code: from a301utils.a301_readfile import download from a301lib.cloudsat import get_geo import glob import os from pathlib import Path import sys import json import numpy as np import h5py from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap rad_file='MYD021KM.A2006303.2220.006.201207814...
11,265
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-ll', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-LL Sub-Topics: Radiative Forcings. ...
11,266
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b> Case study Step1: Some of the data files that are available from AirBase were included in the data folder Step2: Processing a single file We will start with processin...
Python Code: from IPython.display import HTML HTML('<iframe src=http://www.eea.europa.eu/data-and-maps/data/airbase-the-european-air-quality-database-8#tab-data-by-country width=900 height=350></iframe>') Explanation: <p><font size="6"><b> Case study: air quality data of European monitoring stations (AirBase)</b></font...
11,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl 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') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
11,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Using LAMMPS with iPython and Jupyter LAMMPS can be run interactively using iPython easily. This tutorial shows how to set this up. Installation Download the latest version of LAMMPS into a ...
Python Code: from lammps import IPyLammps L = IPyLammps() # 2d circle of particles inside a box with LJ walls import math b = 0 x = 50 y = 20 d = 20 # careful not to slam into wall too hard v = 0.3 w = 0.08 L.units("lj") L.dimension(2) L.atom_style("bond") L.boundary("f f p") L.lattice("hex", 0.85) L.r...
11,269
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook covers using metrics to analyze the 'accuracy' of prophet models. In this notebook, we will extend the previous example (http Step1: Read in the data Read the data in from the...
Python Code: import pandas as pd import numpy as np from fbprophet import Prophet import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error %matplotlib inline plt.rcParams['figure.figsize']=(20,10) plt.style.use('ggplot') Explanation: This notebook covers using metr...
11,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Training and Inference Module We modularized commonly used codes for training and inference in the module (or mod for short) package. This package provides intermediate-level and high-level ...
Python Code: import mxnet as mx from data_iter import SyntheticData # mlp net = mx.sym.Variable('data') net = mx.sym.FullyConnected(net, name='fc1', num_hidden=64) net = mx.sym.Activation(net, name='relu1', act_type="relu") net = mx.sym.FullyConnected(net, name='fc2', num_hidden=10) net = mx.sym.SoftmaxOutput(net, name...
11,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Source of the materials Step1: The 'catch' is that you have to work with SeqRecord objects (see Chapter 4), which contain a Seq object (Chapter 3) plus annotation like an identifier and des...
Python Code: from Bio import SeqIO help(SeqIO) Explanation: Source of the materials: Biopython Tutorial and Cookbook (adapted) Sequence Input/Output In this notebook we'll discuss in more detail the Bio.SeqIO module, which was briefly introduced before. This aims to provide a simple interface for working with assorted ...
11,272
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.0. Co-author Graphs Social network analysis is a popular method in the field of historical network research. By far the most accessible source of information about social networks in scien...
Python Code: from tethne.readers import wos metadata = wos.read('../data/Baldwin/PlantPhysiology', streaming=True, index_fields=['date'], index_features=['authors']) Explanation: 2.0. Co-author Graphs Social network analysis is a popular method in the field of historical network research. By far th...
11,273
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Data We use the "Howell" dataset, which consists of measurements of height, weight, age and sex, of a certain foraging tribe, collected by Nancy Howell. Step2: Empiri...
Python Code: import numpy as np np.set_printoptions(precision=3) import matplotlib.pyplot as plt import math import os import warnings import pandas as pd # from scipy.interpolate import BSpline # from scipy.stats import gaussian_kde !mkdir figures !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro import ...
11,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph Construction and feature engineering Load library Step1: Load data Step2: Graph generation & analysis Build proper edge array Step3: Generate a MultiDigraph with networkx and edge a...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import networkx as nx import pygraphviz as pgv import pydot as pyd from networkx.drawing.nx_agraph import graphviz_layout from networkx.drawing.nx_agraph import write_dot Explanation: Graph Construction and feature en...
11,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn't quite adding up. Specifically, they need you to find the t...
Python Code: for a,b in itertools.permutations(list(map(int, data)), 2): if a+b == 2020: print(a*b) break Explanation: Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn't quite adding up. Specifically, they need you to f...
11,276
Given the following text description, write Python code to implement the functionality described below step by step Description: k-Nearest Neighbor (kNN) exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ...
Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcParams['figure.figsi...
11,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Ants in Space! An introduction to the code in beam_paco__gtoc5 Luís F. Simões 2017-04 <h1 id="tocheading">Table of Contents</h1> <div id="toc"></div> Step1: Taking a look at our Python envi...
Python Code: # https://esa.github.io/pykep/ # https://github.com/esa/pykep # https://pypi.python.org/pypi/pykep/ import PyKEP as pk import numpy as np from tqdm import tqdm, trange import matplotlib.pylab as plt %matplotlib inline import seaborn as sns plt.rcParams['figure.figsize'] = 10, 8 from gtoc5 import * from gto...
11,278
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook downloads and cleans the SCOTUS subnetwork data. It can be modified to create any jurisdiction subnetwork and also the federal appelate subnetwork. You have to modify the two p...
Python Code: # modify these for your own computer repo_directory = '/Users/iaincarmichael/Dropbox/Research/law/law-net/' data_dir = '/Users/iaincarmichael/data/courtlistener/' Explanation: This notebook downloads and cleans the SCOTUS subnetwork data. It can be modified to create any jurisdiction subnetwork and also th...
11,279
Given the following text description, write Python code to implement the functionality described below step by step Description: Car Evaluation using Decision trees and Random Forests <hr> Decision tree learning Decision tree classifiers are attractive models of Machine Learning as they emphasize on interpretability. ...
Python Code: import os from sklearn.tree import DecisionTreeClassifier, export_graphviz import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn import cross_validation, metrics from sklearn.ensemble import RandomForestClassifier from time import time from sklearn import...
11,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create some text Step2: Apply regex
Python Code: # Load regex package import re Explanation: Title: Match A Word Slug: match_a_word Summary: Match A Word Date: 2016-05-01 12:00 Category: Regex Tags: Basics Authors: Chris Albon Based on: Regular Expressions Cookbook Preliminaries End of explanation # Create a variable containing a text string text = 'Th...
11,281
Given the following text description, write Python code to implement the functionality described below step by step Description: COVID19 Exposure Notification System Risk Simulator kpmurphy@google.com, serghiou@google.com (broken link) Last update Step1: Infectiousness vs time since onset of symptoms (TOST) Let $\De...
Python Code: import itertools import numpy as np import matplotlib.pyplot as plt import scipy.stats import pandas as pd from collections import namedtuple from enum import Enum, IntEnum from dataclasses import dataclass import matplotlib.cm as cm import sklearn from sklearn import metrics # Configure plot style sheet p...
11,282
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.algo - Réflexions autour du voyage de commerce (TSP) Le problème du voyageur de commerce consiste à trouver le plus court chemin passant par toutes les villes. On parle aussi de circuit h...
Python Code: %matplotlib inline import random n = 30 x = [ random.random() for _ in range(n) ] y = [ random.random() for _ in range(n) ] import matplotlib.pyplot as plt plt.plot(x,y,"o") Explanation: 2A.algo - Réflexions autour du voyage de commerce (TSP) Le problème du voyageur de commerce consiste à trouver le plus c...
11,283
Given the following text description, write Python code to implement the functionality described below step by step Description: ================================= Decoding sensor space data (MVPA) ================================= Decoding, a.k.a MVPA or supervised machine learning, is applied to MEG data in sensor sp...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression import mne from mne.datasets import sample from mne.decoding import (SlidingEstimator, GeneralizingEstimator, ...
11,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Contact Trajectories Sometimes you're interested in how contacts evolve in a trajectory, frame-by-frame. Contact Map Explorer provides the ContactTrajectory class for this purpose. We'll loo...
Python Code: from __future__ import print_function %matplotlib inline import matplotlib.pyplot as plt import numpy as np from contact_map import ContactTrajectory, RollingContactFrequency import mdtraj as md traj = md.load("data/gsk3b_example.h5") print(traj) # to see number of frames; size of system Explanation: Cont...
11,285
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Open your dataset up using pandas in a Jupyter notebook Step1: 3. Do a .columns to get a feel for your data Step2: 4. Do a .head() to get a feel for your data Step3: 4. Write down 12 q...
Python Code: df Explanation: 1. Open your dataset up using pandas in a Jupyter notebook End of explanation df.columns Explanation: 3. Do a .columns to get a feel for your data End of explanation df.head() Explanation: 4. Do a .head() to get a feel for your data End of explanation df['Agency'].value_counts() print("NASA...
11,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: Let's get started with some basic imports Step2: And then we'll build a synthetic "dataset" and initialize a new bundle with those data Step3: solver_times parameter and o...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: Advanced: solver_times Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe import numpy as np import matplotlib.pyplot a...
11,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Oracle and Python with oracledb This is an example of how to query Oracle from Python Setup and prerequisites This is how you can setup an Oracle instance for testing using a docker image fo...
Python Code: # connect to Oracle using oracledb # !pip install oracledb import oracledb db_user = 'scott' db_connect_string = 'localhost:1521/XEPDB1' db_pass = 'tiger' # To avoid storig connection passwords use getpas or db_config # db_connect_string = 'dbserver:1521/orcl.mydomain.com' # import getpass # db_pass = getp...
11,288
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- 29/10 Archivos de texto. Operaciones con cadenas de caracteres. String formaters. CLASE DE LABORATORIO (Gonzalo) --> Manejo de strings Con los strings podemos hacer muchas operaciones...
Python Code: cadena_caracteres = "Hola mundo" print dir(cadena_caracteres) Explanation: <!-- 29/10 Archivos de texto. Operaciones con cadenas de caracteres. String formaters. CLASE DE LABORATORIO (Gonzalo) --> Manejo de strings Con los strings podemos hacer muchas operaciones: End of explanation print 'Hola mundo' pr...
11,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Student Names Learning Goals (Why are we asking you to do this?) Core Assignment Step1: Experimenting with this simulation A Forest With Thunderbolt & Lightning, Very Very Frightening...
Python Code: # Some setup to load outside web page elements from IPython.display import IFrame # When you execute this cell, it'll reset the simulationb IFrame("http://ncase.me/simulating/model?local=forest/0_growth&play=0&edit=1", width=800, height=400) Explanation: Title Student Names Learning Goals (Why are we askin...
11,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to OnSSET Jupyter Interface¶ This page will guide you through the a simplified version of the OnSSET code, as well as the various parameters that can be set to generate any scenario ...
Python Code: country = 'Malawi' #Dependencies from IPython.display import display, Markdown, HTML import seaborn as sns import matplotlib.pylab as plt import folium import branca.colormap as cm import json %matplotlib inline %run onsset.py Explanation: Welcome to OnSSET Jupyter Interface¶ This page will guide you throu...
11,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Migrating from Spark to BigQuery via Dataproc -- Part 4 Part 1 Step1: Load data into BigQuery Step2: BigQuery queries We can replace much of the initial exploratory code by SQL statements....
Python Code: # Catch-up cell. Run if you did not do previous notebooks of this sequence !wget http://kdd.ics.uci.edu/databases/kddcup99/kddcup.data_10_percent.gz BUCKET='cloud-training-demos-ml' # CHANGE !gsutil cp kdd* gs://$BUCKET/ Explanation: Migrating from Spark to BigQuery via Dataproc -- Part 4 Part 1: The orig...
11,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Minimal Plugin setup Plugins are dedicated analyzer to check the tags of one object at the time. For explanation purpose only, we just here make a plugin that report fountains, it is not loo...
Python Code: %cd "/opt/osmose-backend/" Explanation: Minimal Plugin setup Plugins are dedicated analyzer to check the tags of one object at the time. For explanation purpose only, we just here make a plugin that report fountains, it is not looking for issue in the data. End of explanation from modules.OsmoseTranslation...
11,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Forecasting, updating datasets, and the "news" In this notebook, we describe how to use Statsmodels to compute the impacts of updated or revised datasets on out-of-sample forecasts or in-sam...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt macrodata = sm.datasets.macrodata.load_pandas().data macrodata.index = pd.period_range('1959Q1', '2009Q3', freq='Q') Explanation: Forecasting, updating datasets, and the "news" In this not...
11,294
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a numpy array of different numpy arrays and I want to make a deep copy of the arrays. I found out the following:
Problem: import numpy as np pairs = [(2, 3), (3, 4), (4, 5)] array_of_arrays = np.array([np.arange(a*b).reshape(a,b) for (a, b) in pairs]) import copy result = copy.deepcopy(array_of_arrays)
11,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to ConPy Step1: Loading the simulation data If the code in the above cell ran without any errors, we're good to go. Let's load the stimulation data. It is stored as an MNE-Python Epoc...
Python Code: # Don't worry about warnings in this exercise, as they can be distracting. import warnings warnings.simplefilter('ignore') # Import the required Python modules import mne import conpy import surfer # Import and configure the 3D graphics backend from mayavi import mlab mlab.init_notebook('png') # Tell MNE-P...
11,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Run mcode on the adjacency list for your toy graph, with vwp=0.8 Load the Krogan et al. network edge-list data as a Pandas data frame Step1: Make an igraph graph and print its summary Step2...
Python Code: edge_list = Explanation: Run mcode on the adjacency list for your toy graph, with vwp=0.8 Load the Krogan et al. network edge-list data as a Pandas data frame End of explanation krogan_graph = krogan_graph.summary() Explanation: Make an igraph graph and print its summary End of explanation res = Explana...
11,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Unsupervised Anomaly Detection Anomaly detection detects data points in data that does not fit well with the rest of data. In this notebook we demonstrate how to do anomaly detection for 1-D...
Python Code: import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df_1932 = pd.read_csv("m_1932.csv", header=None, usecols=[1,2,3], names=["time_step", "cpu_usage","mem_usage"]) Explanation: Unsupervised Anomaly Detection Anomaly detection detects data points in data that...
11,298
Given the following text description, write Python code to implement the functionality described below step by step Description: SpectralAnalysis showcase I've written a library for regular plotting and curve fitting that is much, much nicer than the FittingRoutines module. In this notebook I'll be showing off (I gues...
Python Code: testmodel = Model("Test") # set up a test model with linear fit Explanation: SpectralAnalysis showcase I've written a library for regular plotting and curve fitting that is much, much nicer than the FittingRoutines module. In this notebook I'll be showing off (I guess in a README-esque way) of how all...
11,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Whiskey Data This data set contains data on a small number of whiskies Step1: Summaries Shown below are the following charts Step2: Some Analysis Here we use the sci-kit decision tree regr...
Python Code: import pandas as pd from numpy import log, abs, sign, sqrt import ibmcognitive ibmcognitive.brunel.set_brunel_service_url("http://localhost:8080/BrunelServices") data = pd.read_csv("data/whiskey.csv") print('Data on whiskies:', ', '.join(data.columns)) Explanation: Whiskey Data This data set contains data ...