Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
13,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This iPython notebook is a very basic example of how to read in and manipulate data using the GWpy software package. If you have LIGO.org authentication, instructions on how to run this iPyt... | Python Code:
# Inline matplotlib only needed for iPython notebooks for inline image rendering
# If running this code in a script, matplotlib inline can be commented out or omitted
%matplotlib inline
from gwpy.timeseries import TimeSeries
data = TimeSeries.fetch_open_data('L1', 1126259446, 1126259478)
# on a LIGO Data G... |
13,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Next block caches metadata for retrieving Supreme Court transcripts into a csv
Step1: Should put a csv reading block here for faster processing | Python Code:
import csv
with open("judicialMetadata.csv", "w+") as metadata:
header = allRecentRecords[0].keys()
writer = csv.DictWriter(metadata, fieldnames=header)
writer.writerows(allRecentRecords)
Explanation: Next block caches metadata for retrieving Supreme Court transcripts into a csv
End of explanat... |
13,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forecast Tutorial
This tutorial will walk through forecast data from Unidata forecast model data using the forecast.py module within pvlib.
Table of contents
Step1: GFS (0.5 deg)
Step2: GF... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
# built in python modules
import datetime
import os
# python add-ons
import numpy as np
import pandas as pd
# for accessing UNIDATA THREDD servers
from siphon.catalog import TDSCatalog
from siphon.ncss import NCSS
import pvlib
from pvlib.forecast import GF... |
13,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core... |
13,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Hardware Design
This code works through the hardware design process with the the
audience of software developers more in mind. We start with the simple
problem of designing ... | Python Code:
import pyrtl
Explanation: Introduction to Hardware Design
This code works through the hardware design process with the the
audience of software developers more in mind. We start with the simple
problem of designing a fibonacci sequence calculator (http://oeis.org/A000045).
End of explanation
def software_... |
13,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Somme de variables aléatoires
Step1: Somme de deux v.a. discrètes
Step2: Paramètre $p$ différent (TODO)
TODO
Step3: Somme de deux v.a. suivant une loi de poisson
Si $X_1 \sim \mathcal{P}(... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
Explanation: Somme de variables aléatoires
End of explanation
p = 0.5
n1 = 5
n2 = 8
# Empirical distribution
num_samples = 1000000
x1 = np.random.binomial(n=n1, p=p, size=num_samples)
x2 = np.random.binomial(n=n2, p=p,... |
13,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
Step1: Exploring the Fermi distribution
In quantum statistics, the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
Explanation: Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
End of... |
13,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Manipulation with skimage
This example builds a simple UI for performing basic image manipulation with scikit-image.
Step1: Let's load an image from scikit-image's collection, stored ... | Python Code:
# Stdlib imports
from io import BytesIO
# Third-party libraries
from IPython.display import Image
from ipywidgets import interact, interactive, fixed
import matplotlib as mpl
from skimage import data, filters, io, img_as_float
import numpy as np
Explanation: Image Manipulation with skimage
This example bui... |
13,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table Visualization
This section demonstrates visualization of tabular data using the Styler
class. For information on visualization with charting please see Chart Visualization. This docume... | 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
import matplotlib as mpl
df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]],
index=pd.Index(... |
13,809 | 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... |
13,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Sanity Check for PartialFlow Training
This notebook is a toy example for comparing the training of a network with and without PartialFlow involved. We define two small neural networks ... | Python Code:
import tensorflow as tf
import numpy as np
# load MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
train_images = np.reshape(mnist.train.images, [-1, 28, 28, 1])
train_labels = mnist.train.labels
test_images = np.reshape(mn... |
13,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tracking mutation frequencies
Step1: Run a simulation
Step2: Group mutation trajectories by position and effect size
Max mutation frequencies
Step3: The only fixation has an 'esize' $> 0$... | Python Code:
%matplotlib inline
%pylab inline
import fwdpy as fp
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import copy
Explanation: Tracking mutation frequencies
End of explanation
nregions = [fp.Region(0,1,1),fp.Region(2,3,1)]
sregions = [fp.ExpS(1,2,1,-0.1),fp.ExpS(1,2,0.01,0.001)]
rregion... |
13,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Do some initial testing and analysis
Step1: Import all data (data was previously cleaning in other notebooks)
Step2: Now I have one dict with metro stations and one with bike stations
Step... | Python Code:
import pickle
from geopy.distance import vincenty
Explanation: Do some initial testing and analysis
End of explanation
station_data = pickle.load( open( "station_data.p", "rb" ) )
bike_location = pickle.load( open( "bike_location.p", "rb" ) )
Explanation: Import all data (data was previously cleaning in ot... |
13,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Filter
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
<table align="left" style="margin-right
Step2: Examples
In the follow... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... |
13,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook, I briefly demonstrate the use of ProximityCellMatch and BestProximityCellMatch tables in meso
Step1: Following demonstrates how to find matches between source scan
Step2: ... | Python Code:
from pipeline import meso
Explanation: In this notebook, I briefly demonstrate the use of ProximityCellMatch and BestProximityCellMatch tables in meso
End of explanation
source_scan = dict(animal_id=25133, session=3, scan_idx=11)
target_scan = dict(animal_id=25133, session=4, scan_idx=13)
Explanation: Foll... |
13,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Color-color plots for LRG targets
The goal of this notebook is to compare the colors of LRG targets against those of the LRG templates.
Step2: Read the targets catalog
Step3: Read the temp... | Python Code:
import os
from time import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import fitsio
import seaborn as sns
from speclite import filters
from desitarget import desi_mask
from desisim.io import read_basis_templates
%pylab inline
sns.set(style='white', font_scale... |
13,816 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a numpy array which contains time series data. I want to bin that array into equal partitions of a given length (it is fine to drop the last partition if it is not the same s... | Problem:
import numpy as np
data = np.array([4, 2, 5, 6, 7, 5, 4, 3, 5, 7])
bin_size = 3
bin_data_mean = data[:(data.size // bin_size) * bin_size].reshape(-1, bin_size).mean(axis=1) |
13,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
연습문제
아래 문제들을 해결하는 코드를 W04-Exc.py 파일에 작성하여 제출하라.
연습 1
양의 정수 n을 입력 받아 0과 1 사이의 값을 n등분하는 숫자들의
리스트를 리턴하는 함수 n_divide(n)을 작성하라. (힌트
Step1: 연습 2
문장을 인자로 받으면 문장에 사용된 단어들을 차례대로 print하는 함수
sen2wor... | Python Code:
def n_divide(n):
L = []
for i in range(n+1):
L.append(i * 1.0/n)
return L
n_divide(10)
Explanation: 연습문제
아래 문제들을 해결하는 코드를 W04-Exc.py 파일에 작성하여 제출하라.
연습 1
양의 정수 n을 입력 받아 0과 1 사이의 값을 n등분하는 숫자들의
리스트를 리턴하는 함수 n_divide(n)을 작성하라. (힌트: range 함수 활용)
예제:
In [1]: n_divide(10)
out[1]: [0, 0.1, ... |
13,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scikit-learn-random forest
Credits
Step1: Random Forest Classifier
Random forests are an example of an ensemble learner built on decision trees.
For this reason we'll start by discussing de... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn;
from sklearn.linear_model import LinearRegression
from scipy import stats
import pylab as pl
seaborn.set()
Explanation: scikit-learn-random forest
Credits: Forked from PyCon 2015 Scikit-learn Tutorial by Jake VanderPlas
... |
13,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Forest Fire Model
A rapid introduction to Mesa
The Forest Fire Model is one of the simplest examples of a model that exhibits self-organized criticality.
Mesa is a new, Pythonic agent-ba... | Python Code:
import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import Grid
from mesa.datacollection import DataCollector
from mesa.batchrunner import BatchRunner
Explanation: The Forest Fire Model
A ra... |
13,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing cellpy batch - preparing the data
{{cookiecutter.project_name}}
Step1: Creating pages and initialise the cellpy batch object
If you need to create Journal Pages, please provide a... | Python Code:
import sys
import cellpy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from cellpy import prms
from cellpy import prmreader
from cellpy.utils import batch, plotutils
%matplotlib inline
print(f"cellpy version: {cellpy.__version__}")
Explanation: Processing cellpy batch - preparing t... |
13,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSE 6040, Fall 2015 [09]
Step1: sqlite maintains databases as files; in this example, the name of that file is example.db.
If the named file does not yet exist, connecting to it in this way... | Python Code:
import sqlite3 as db
# Connect to a database (or create one if it doesn't exist)
conn = db.connect ('example.db')
Explanation: CSE 6040, Fall 2015 [09]: Relational Databases via SQL
Today's lab is a crash-course in relational databases, as well as SQL (Structured Query Language), which is the most popular ... |
13,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook has been tested with
Python 3.5
Keras 2.0.8
Tensorflow 1.3.0
Step1: Use VGG16 model with pre-trained weights
Keras documentation for detail
Step2: Use only convolutional part... | Python Code:
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.layers import Input, Flatten, Dense
from keras.models import Model
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
Explanatio... |
13,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predict the Sun Hours by Decision Tree
Import Modules
Step1: Import Data
Below is the Daily Weather Observations of Sydney, New South Wales between Aug 2015 and Aug 2016.
Step2: Column Mea... | Python Code:
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from IPython.display import Image
from sklearn.externals.six import StringIO
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
RANDOM_SEED = 9
Expla... |
13,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 语言翻译
在此项目中,你将了解神经网络机器翻译这一领域。你将用由英语和法语语句组成的数据集,训练一个序列到序列模型(sequence to sequence model),该模型能够将新的英语句子翻译成法语。
获取数据
因为将整个英语语言内容翻译成法语需要大量训练时间,所以我们提供了一小部分的英语语料库。
Step3: 探索数据
研究 view_sentence... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: 语言翻译
在此项目中,你将了解神经网络机器翻译这一领域。你将用由英语和法语语句组成的数据集,训练一个序... |
13,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
automaton.coaccessible
Create a new automaton from the coaccessible part of the input, i.e., the subautomaton whose states can be reach a final state.
Preconditions
Step1: The following aut... | Python Code:
import vcsn
Explanation: automaton.coaccessible
Create a new automaton from the coaccessible part of the input, i.e., the subautomaton whose states can be reach a final state.
Preconditions:
- None
Postconditions:
- Result.is_coaccessible
See also:
- automaton.is_coaccessible
- automaton.accessible
- autom... |
13,826 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following kind of strings in my column seen below. I would like to parse out everything after the last _ of each string, and if there is no _ then leave the string as-is.... | Problem:
import pandas as pd
strs = ['Stackoverflow_1234',
'Stack_Over_Flow_1234',
'Stackoverflow',
'Stack_Overflow_1234']
df = pd.DataFrame(data={'SOURCE_NAME': strs})
def g(df):
df['SOURCE_NAME'] = df['SOURCE_NAME'].str.rsplit('_', 1).str.get(0)
return df
df = g(df.copy()) |
13,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: version 1.0.1
+
Web Server Log Analysis with Apache Spark
This lab will demonstrate how easy it is to perform web server log analysis with Apache Spark.
Server log analysis is an id... | Python Code:
import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
Convert Apache time format into a Python datetime object
Args:
s (str): date... |
13,828 | 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'
class DLProgress(tqdm):
last_block = 0
def h... |
13,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corrugated Shells
Init symbols for sympy
Step1: Corrugated cylindrical coordinates
Step2: Base Vectors $\vec{R}_1, \vec{R}_2, \vec{R}_3$
Step3: Base Vectors $\vec{R}^1, \vec{R}^2, \vec{R}... | Python Code:
from sympy import *
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
x1, x2, x3 = symbols("x_1 x_2 x_3")
alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3")
R, L, ga, gv = symbols("R L g_a g_v")
init_printing()
Explanation: Corrugated Shells
Init symbols for sympy
End of explanation
a1 = pi ... |
13,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Exercises about Numpy
Author
Step5: This notebook reviews some of the Python modules that make it possible to work with data structures in an easy an efficient manner. We will review... | Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
import numpy as np
import hashlib
# Test functions
def hashstr(str1):
Implements the secure hash of a string
return hashlib.sha1(str1).hexdigest()
def test_arrayequal(x1, x2, err_msg, ok_msg='Test passed'):
... |
13,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Setup lightning
Step2: Iris
Step3: CIFAR | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import os
assert os.environ["COLAB_TPU_ADDR"], "Make sure to select TPU from Edit > Notebook settings > Hardware accelerator"
#!pip install -q cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.8-cp37-cp37m-linux_x86_64.wh... |
13,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python范儿:Coding Pythonically
1 数学定义:解析(Comprehensions,或称推导式)
1.1 让代码飞
找到0-9之间的偶数
Step1: 我们做的事情在数学定义上看来像是什么呢?
${x|x \in {0,1,2,....,9}, s.t. x\%2==0 }$
Step2: 这种代码形式称为Comprehensions,也就是解析(推... | Python Code:
#number = range(10)
size = 10
even_numbers = []
n = 0
while n < size:
if n % 2==0:
even_numbers.append(n)
n += 1
print even_numbers
Explanation: Python范儿:Coding Pythonically
1 数学定义:解析(Comprehensions,或称推导式)
1.1 让代码飞
找到0-9之间的偶数
End of explanation
{ x for x in range(10) if x % 2==0 }
Explanat... |
13,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Viewing and manipulating FITS images
Authors
Lia Corrales, Kris Stern, Stephanie T. Douglas, Kelle Cruz
Learning Goals
Open FITS files and load image data
Make a 2D histogram with image data... | Python Code:
import numpy as np
# Set up matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
from astropy.io import fits
Explanation: Viewing and manipulating FITS images
Authors
Lia Corrales, Kris Stern, Stephanie T. Douglas, Kelle Cruz
Learning Goals
Open FITS files and load image data
Make a 2D histogram w... |
13,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trying out features
Learning Objectives
Step1: Next, we'll load our data set.
Step2: Examine and split the data
It's a good idea to get to know your data a little bit before you work with ... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.5
import math
import shutil
import numpy as np
import pandas as pd
import tensorflow as tf
print(tf.__version__)
tf.compat.v1.logging.set_verbosity(tf.c... |
13,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Translating French to English with Pytorch
Step1: Prepare corpus
The French-English parallel corpus can be downloaded from http
Step2: To make this problem a little simpler so we can train... | Python Code:
%matplotlib inline
import re, pickle, collections, bcolz, numpy as np, keras, sklearn, math, operator
from gensim.models import word2vec, KeyedVectors # - added KeyedVectors.load_word2vec_format
import torch, torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functi... |
13,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
auto_arima
Pmdarima bring R's auto.arima functionality to Python by wrapping statsmodel ARIMA and SARIMAX models into a singular scikit-learn-esque estimator (pmdarima.arima.ARIMA) and addin... | Python Code:
import numpy as np
import pmdarima as pm
print('numpy version: %r' % np.__version__)
print('pmdarima version: %r' % pm.__version__)
Explanation: auto_arima
Pmdarima bring R's auto.arima functionality to Python by wrapping statsmodel ARIMA and SARIMAX models into a singular scikit-learn-esque estimator (pmd... |
13,837 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<img src="http
Step1: Warning
Step2: <div id='example2' />
Example 2
Back to toc
Considere el siguiente BVP
Step3: <div id='example3s' />
Example 3
Back to toc
Considere que ... | Python Code:
import numpy as np
import scipy as sp
# To solve IVP, notice this is different that odeint!
from scipy.integrate import solve_ivp
# To integrate use one of the followings:
from scipy.integrate import quad, quadrature, trapezoid, simpson
# For least-square problems
from scipy.sparse.linalg import lsqr
from ... |
13,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$ \LaTeX \text{ command declarations here.}
\newcommand{\N}{\mathcal{N}}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\norm}[1]{\|#1\|_2}
\newcommand{\d}{\mat... | Python Code:
%pylab inline
import numpy as np
center1 = np.array([3.0,3.0])
center2 = np.array([-3.0,-3.0])
X = np.zeros((100,2)); Y = np.zeros((100,))
X[:50,:] = np.random.multivariate_normal(center1, np.eye(2),(50,))
Y[:50] = +1
X[50:,:] = np.random.multivariate_normal(center2, np.eye(2),(50,))
Y[50:] = -1
plt.scatte... |
13,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Variability of the Sample Mean
By the Central Limit Theorem, the probability distribution of the mean of a large random sample is roughly normal. The bell curve is centered at the popula... | Python Code:
united = Table.read_table('http://inferentialthinking.com/notebooks/united_summer2015.csv')
delay = united.select('Delay')
pop_mean = np.mean(delay.column('Delay'))
pop_mean
delay_opts = {
'xlabel': 'Delay (minute)',
'ylabel': 'Percent per minute',
'xlim': (-20, 200),
'ylim': (0, 0.037),
... |
13,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maquetación Python 3 (Markdown)
Step1: Encabezado de tres "###"
Encabezado de cinco "#####"
Step2: texto en cursiva
texto en negrita
asteriscos y cursiva en una sola línea
~~texto tachado~... | Python Code:
# Los HEADERS o encabezados se definen mediante #, existen 6 niveles siendo un sólo # el de mayor tamaño y ###### el de menor
# Ejemplo:
Explanation: Maquetación Python 3 (Markdown)
End of explanation
# Emphasis o estilos del texto
# *cursiva*
# **negrita**
# ~~tachado~~
# Ejemplos:
Explanation: Encabezado... |
13,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Custom Observer
This example defines a plane-observer in python.
Step3: As test, we propagate some particles in a random field with a sheet observer
Step4: and plot the final positi... | Python Code:
import crpropa
class ObserverPlane(crpropa.ObserverFeature):
Detects all particles after crossing the plane. Defined by position (any
point in the plane) and vectors v1 and v2.
def __init__(self, position, v1, v2):
crpropa.ObserverFeature.__init__(self)
# calculate thr... |
13,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rechunking
Rechunking lets us re-distribute how datasets are split between variables and chunks across a Beam PCollection.
To get started we'll recreate our dummy data from the data model tu... | Python Code:
import apache_beam as beam
import numpy as np
import xarray_beam as xbeam
import xarray
def create_records():
for offset in [0, 4]:
key = xbeam.Key({'x': offset, 'y': 0})
data = 2 * offset + np.arange(8).reshape(4, 2)
chunk = xarray.Dataset({
'foo': (('x', 'y'), data... |
13,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Preparation
Introduction
Data Collection
Data Preprocessing
Building and Training the Model
Qualitative Analysis of Player Vectors
t-SNE
PCA
ScatterPlot3D
Player Algebra
Ne... | Python Code:
import urllib.request
import zipfile
from os import makedirs
from os.path import exists
project_directory = "/home/airalcorn2/Projects/batter_pitcher_2vec/batter-pitcher-2vec/" # Change this.
zip_name = "2010seve"
data_directory = project_directory + zip_name
if not exists(data_directory):
makedirs(pro... |
13,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Combine constructiveness and toxicity annotations from different batches
Step1: Write contructiveness and toxicity combined CSV | Python Code:
dfs = []
for batch in batches:
filename = aggregated_data_path + 'batch' + str(batch) + '_constructiveness_and_toxicity_combined.csv'
dfs.append(pd.read_csv(filename))
combined_annotations_df = pd.concat(dfs)
# Sort the merged dataframe on constructiveness and toxicity
combined_annotations_df.shape... |
13,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 3
Imports
Step2: Contour plots of 2d wavefunctions
The wavefunction of a 2d quantum well is
Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 3
Imports
End of explanation
def well2d(x, y, nx, ny, L=1.0):
Compute the 2d quantum well wave function.
sci=2/L*np.sin((nx*np.pi*x)/L)*np.sin((ny*np.pi*y)/L)
return sci
psi = well2d(np.linspa... |
13,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PDE
The acoustic wave equation for the square slowness m and a source q is given in 3D by
Step1: Time and space discretization as a Taylor expansion.
The time discretization is define as ... | Python Code:
p=Function('p')
m,s,h = symbols('m s h')
m=M(x,y,z)
q=Q(x,y,t)
d=D(x,y,t)
e=E(x,y)
Explanation: PDE
The acoustic wave equation for the square slowness m and a source q is given in 3D by :
\begin{cases}
&m \frac{d^2 u(x,t)}{dt^2} - \nabla^2 u(x,t) =q \
&u(.,0) = 0 \
&\frac{d u(x,t)}{dt}|_{t=0} = 0
\en... |
13,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Python for fun and profit
Juan Luis Cano Rodríguez
Madrid, 2016-05-13 @ ETS Asset Management Factory
Outline
Introduction
Python for Data Science
Python for IT
General advice
Conclusi... | Python Code:
from ipywidgets import interact, fixed
from sympy import init_printing, Symbol, Eq, factor
init_printing(use_latex=True)
x = Symbol('x')
def factorit(n):
return Eq(x**n-1, factor(x**n-1))
interact(factorit, n=(2,40))
# Import matplotlib (plotting), skimage (image processing) and interact (user interfac... |
13,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="coastline_classifier_top"></a>
Coastline Classifier
This coastal boundary algorithm is used to classify a given pixel as either coastline or not coastline using a simple binary format... | Python Code:
import scipy.ndimage.filters as conv
import numpy as np
def _coastline_classification(dataset, water_band='wofs'):
kern = np.array([[1, 1, 1], [1, 0.001, 1], [1, 1, 1]])
convolved = conv.convolve(dataset[water_band], kern, mode='constant') // 1
ds = dataset.where(convolved > 0)
ds = ds.wher... |
13,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capability is not a stochastic geometry capability lik... | Python Code:
%matplotlib inline
from math import pi
import numpy as np
import matplotlib.pyplot as plt
import openmc
import openmc.model
Explanation: OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capability is not a stochastic geo... |
13,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Connexion
Connexion is a python framework based on Flask.
It streamlines the creation of contract-first REST APIs.
Once you have your OAS3 spec, connexion uses it to
Step1: Now run the spe... | Python Code:
# At first ensure connexion is installed
# together with the swagger module used to render the OAS3 spec
# in the web-ui
!pip install connexion[swagger-ui] connexion
Explanation: Connexion
Connexion is a python framework based on Flask.
It streamlines the creation of contract-first REST APIs.
Once you hav... |
13,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Sample data
Step3: A function to calculate three parameter transformation based on commmon points. The point coordinates are stored in dictionaries, the key is the po... | Python Code:
import numpy as np
from math import atan2, sqrt, sin, cos, pi
import re
X, Y, Z, MX, MY, MZ = 0, 1, 2, 3, 4, 5 # indices in coord dictionary items
RO = 180 * 3600 / pi
Explanation: <a href="https://colab.research.google.com/github/OSGeoLabBp/tutorials/blob/master/english/data_processing/lessons/trans.ipy... |
13,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
These notes follow the official python tutorial pretty closely
Step1: Lists
Lists group together data. Many languages have arrays (we'll look at those in a bit in python). But unlike arra... | Python Code:
from __future__ import print_function
Explanation: These notes follow the official python tutorial pretty closely: http://docs.python.org/3/tutorial/
End of explanation
a = [1, 2.0, "my list", 4]
print(a)
Explanation: Lists
Lists group together data. Many languages have arrays (we'll look at those in a bi... |
13,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditions in Python
Python has a very natural looking syntax for conditionals and boolean operations
if statment in Python
if True
Step1: if else statement
Step2: if - else if Statment
Py... | Python Code:
import random
toss = random.random() # returns a random value between 0 and 1
if toss > 0.5:
print 'I won'
Explanation: Conditions in Python
Python has a very natural looking syntax for conditionals and boolean operations
if statment in Python
if True:
do something
End of explanation
toss = ra... |
13,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TF-Agents Authors.
Step1: 环境
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step9: Python 环境
Python 环境的 step(action) -> n... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
13,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example analysis of Spark metrics collected with sparkMeasure
This is an example analysis of workload metrics collected with sparkMeasure https
Step1: Read data from storage and register as... | Python Code:
# This is the file path and name where the metrics are stored
metrics_filename = "<path>/myPerfTaskMetrics1"
# This defines the time window for analysis
# when using metrics coming from taskMetrics.runAndMeasure,
# get the info from: taskMetrics.beginSnapshot and taskMetrics.endSnapshot
# if you don't hav... |
13,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table width="100%" border="0">
<tr>
<td><img src="./images/ing.png" alt="" align="left" /></td>
<td><img src="./images/ucv.png" alt="" align="center" height="100" width="100" /></... | Python Code:
from __future__ import print_function
from IPython.html.widgets import interact, interactive, fixed
from IPython.html import widgets
Explanation: <table width="100%" border="0">
<tr>
<td><img src="./images/ing.png" alt="" align="left" /></td>
<td><img src="./images/ucv.png" alt="" align="center" ... |
13,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visual Diagnosis of Text Analysis with Baleen
This notebook has been created as part of the Yellowbrick user study. I hope to explore how visual methods might improve the workflow of text cl... | Python Code:
%matplotlib inline
import os
import sys
import nltk
import pickle
# To import yellowbrick
sys.path.append("../..")
Explanation: Visual Diagnosis of Text Analysis with Baleen
This notebook has been created as part of the Yellowbrick user study. I hope to explore how visual methods might improve the work... |
13,858 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle San Francisco Crime Classification
Berkeley MIDS W207 Final Project
Step1: Local, individual load of updated data set (with weather data integrated) into training, development, and t... | Python Code:
# Additional Libraries
%matplotlib inline
import matplotlib.pyplot as plt
# Import relevant libraries:
import time
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.preproce... |
13,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
13,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Встроенная-сортировка" data-toc-modified-id="Встроенная-сортировка-1">Встроенная со... | Python Code:
a = [5, 3, -2, 9, 1]
# Метод sort меняет существующий список
a.sort()
print(a)
Explanation: <h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Встроенная-сортировка" data-toc-modified-id="Встроенная-сортировка-1">Встроенная сортировка</a></span></li><... |
13,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: One solution
Below is one way to use a class to do this
I'm not a software developer in python, so there may be much nicer ways, but this ought to be good enough. The... | Python Code:
import numpy as np
def mySimpleSolver(f,x0,maxIters=13):
x = np.asarray(x0,dtype='float64').copy()
for k in range(maxIters):
fx = f(x)
x -= .001*x # some weird update rule, just to make something interesting happen
return x
# Let's solve this in 1D
f = lambda x : x**2
x = mySimpleSolver( f, ... |
13,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collaborative Filtering
This is a starter notebook forked from last year's competition. This is an implementation of Collaborative filtering starter with Keras. Uses only the win(1) and loss... | Python Code:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, ... |
13,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Constraint Satisfaction Problems Lab
Introduction
Constraint Satisfaction is a technique for solving problems by expressing limits on the values of each variable in the solution with mathema... | Python Code:
import copy
import timeit
import matplotlib as mpl
import matplotlib.pyplot as plt
from util import constraint, displayBoard
from sympy import *
from IPython.display import display
init_printing()
%matplotlib inline
Explanation: Constraint Satisfaction Problems Lab
Introduction
Constraint Satisfaction is a... |
13,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 2
Imports
Step1: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the propertie... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 2
Imports
End of explanation
!head -n 30 open_exoplanet_catalogue.txt
Explanation: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The followin... |
13,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let us first explore an example that falls under novelty detection. Here, we train a model on data with some distribution and no outliers. The test data, has some "novel" subset of data th... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
%matplotlib inline
Explanation: Let us first explore an example that falls under novelty detection. Here, we train a model on data with some distribution and no outliers. The test data, has some "novel" subset of data that does no... |
13,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Upper Air Analysis using Declarative Syntax
The MetPy declarative syntax allows for a simplified interface to creating common
meteorological analyses including upper air observation plots.
S... | Python Code:
from datetime import datetime
import pandas as pd
from metpy.cbook import get_test_data
import metpy.plots as mpplots
from metpy.units import units
Explanation: Upper Air Analysis using Declarative Syntax
The MetPy declarative syntax allows for a simplified interface to creating common
meteorological analy... |
13,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
notes
Now I know I should think in column vector, and Tensorflow is very picky about the shape of data. But in numpy, the normal 1D ndarray is represented as column vector already. If I resh... | Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
import sys
sys.path.append('..')
from helper import logistic_regression as lr # my own module
from helper import general as ... |
13,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
¿Qué es programar?
Un programa de ordenador es una serie de instrucciones que le dicen a la máquina qué tiene que hacer. Las máquinas no entienden nuestro lenguaje, por lo que tenemos que ap... | Python Code:
print("Hola mundo!")
Explanation: ¿Qué es programar?
Un programa de ordenador es una serie de instrucciones que le dicen a la máquina qué tiene que hacer. Las máquinas no entienden nuestro lenguaje, por lo que tenemos que aprender un lenguaje para poder comunicarnos con ellas y darles órdenes. Hay muchísim... |
13,869 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recursive Algorithm
Step1: This let's us derive a recurisve form.
$Y = \Theta X$
$Y X^T = \Theta X X^T$
We accumulate $Y X^T$ and $X X^T$ since they are of fixed size
and there is a recurs... | Python Code:
import sympy
sympy.init_printing()
Theta = sympy.Matrix(sympy.symbols(
'theta_0:3_0:4')).reshape(3,4)
def Y(n):
return sympy.Matrix(sympy.symbols(
'G_x:z_0:{:d}'.format(n+1))).T.reshape(3, n+1)
def C(n):
return sympy.ones(n+1, 1)
def T(n):
return sympy.Matrix(sympy.symbols('T_0:{:d}... |
13,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
COMP 3314 Assignment 1
<br><br>
Nian Xiaodong (3035087112)
Python + ipynb
The goal of this assignment is to learn/review python and ipynb.
Python is a popular programming language, and also... | Python Code:
# the function
def sort(values):
# insert your code here
for j in range(len(values)-1,0,-1):
for i in range(0, j):
if values[i] > values[i+1]:
values[i], values[i+1] = values[i+1], values[i]
return values
# main
import numpy as np
# different random seed
np.r... |
13,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Photonic design in dphox
At a glance
In this tutorial, the goal is to demonstrate how practical photonic devices can be designed efficiently in dphox.
Along the way, the following advantages... | Python Code:
import dphox as dp
import numpy as np
import holoviews as hv
from trimesh.transformations import rotation_matrix
hv.extension('bokeh')
import warnings
warnings.filterwarnings('ignore') # ignore shapely warnings
Explanation: Photonic design in dphox
At a glance
In this tutorial, the goal is to demonstrate ... |
13,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
13,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learners
In this section, we will introduce several pre-defined learners to learning the datasets by updating their weights to minimize the loss function. when using a learner to deal with m... | Python Code:
import os, sys
sys.path = [os.path.abspath("../../")] + sys.path
from deep_learning4e import *
from notebook4e import *
from learning4e import *
Explanation: Learners
In this section, we will introduce several pre-defined learners to learning the datasets by updating their weights to minimize the loss func... |
13,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning a Reward Function using Preference Comparisons
The preference comparisons algorithm learns a reward function by comparing trajectory segments to each other.
To set up the preference... | Python Code:
from imitation.algorithms import preference_comparisons
from imitation.rewards.reward_nets import BasicRewardNet
from imitation.util.networks import RunningNorm
from imitation.policies.base import FeedForward32Policy, NormalizeFeaturesExtractor
import seals
import gym
from stable_baselines3.common.vec_env ... |
13,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wrangle Volume Data
We wrangle the traffic volume data into a workable format, and extract just the site and detector we are interested in.
Import data
Step1: Filter data
Filter to site 243... | Python Code:
import pandas as pd
f = pd.read_csv('../data/VSDATA_20150819.csv')
Explanation: Wrangle Volume Data
We wrangle the traffic volume data into a workable format, and extract just the site and detector we are interested in.
Import data
End of explanation
vols = f[(f["NB_SCATS_SITE"] == 2433) & f["NB_DETECTOR"]... |
13,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Settings
Step1: 4. Looking at the data
Summaries
Step2: Cycles
Step3: Selecting specific cells and investigating them
Step4: Let's see how the smoothing (interpolation) method works
S... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cellpy
from cellpy import log
from cellpy import cellreader
from cellpy import prms
from cellpy import prmreader
from cellpy.utils import batch
# import holoviews as hv
%matplotlib inline
# hv.e... |
13,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Auto-provision a new user
Create a home directory
Create NFS export
Create SMB share
Create quota
Set up daily snapshots
Prerequisites
Install the qumulo api via pip install qumulo_api, or d... | Python Code:
cluster = 'XXXXX' # Qumulo cluster hostname or IP where you're setting up users
api_user = 'XXXXX' # Qumulo api user name
api_password = 'XXXXX' # Qumulo api password
base_dir = 'XXXXX' # the parent path where the users will be created.
user_name = 'XXXXX' # the new "user" to set up.
import os
impor... |
13,878 | 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="#Quality-control" data-toc-modified-id="Quality-control-1"><span class="toc-item-num">1 </span>Quality control</a></div><d... | Python Code:
# important stuff:
import os
import pandas as pd
import numpy as np
# morgan
import morgan as morgan
import gvars
import genpy
# stats
from scipy import stats as sts
# Graphics
import matplotlib as mpl
import matplotlib.ticker as plticker
import matplotlib.pyplot as plt
import seaborn as sns
import matplot... |
13,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: オートエンコーダの基礎
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: データセットを読み込む
まず、Fashion MNIST デー... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
13,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation Exercise 2
Step1: Sparse 2d interpolation
In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain
Step2: The follow... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
from scipy.interpolate import interp1d
from scipy.interpolate import interp2d
Explanation: Interpolation Exercise 2
End of explanation
xb=np.array([-5,-4... |
13,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fourier Conduction
This examples shows how OpenPNM can be used to simulate thermal conduction on a generic grid of nodes. The result obtained from OpenPNM is compared to the analytical resul... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
np.random.seed(10)
ws = op.Workspace()
ws.settings["loglevel"] = 40
np.set_printoptions(precision=5)
Explanation: Fourier Conduction
This examples shows how OpenPNM can be used to si... |
13,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Matplotlib
matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality... | Python Code:
%matplotlib notebook
import matplotlib.pyplot as plt
Explanation: Introduction to Matplotlib
matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore m... |
13,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example Assessment
After installing PyGauss you should be able to open this IPython Notebook from;
https
Step1: The test folder has a number of example Gaussian outputs to play around with.... | Python Code:
from IPython.display import display, Image
%matplotlib inline
import pygauss as pg
print 'pygauss version: {}'.format(pg.__version__)
Explanation: Example Assessment
After installing PyGauss you should be able to open this IPython Notebook from;
https://github.com/chrisjsewell/PyGauss/blob/master/Example_A... |
13,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 3
Imports
Step2: Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 3
Imports
End of explanation
np.sech?
def soliton(x, t, c, a):
Return phi(x, t) for a soliton wave ... |
13,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word Frequency in Literary Text
Click on the play icon above to "run" each box of code.
This program generates a table of how often words appear in a file and sorts them to show the ones the... | Python Code:
import re
import pandas as pd
import urllib.request
frequency = {}
document_text = urllib.request.urlopen \
('http://www.textfiles.com/etext/FICTION/bronte-jane-178.txt') \
.read().decode('utf-8')
text_string = document_text.lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for ... |
13,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Norm approximation on restricted quantized domain
Fast approximation of the norm over the value of a 10bit unsigned int
using batch gradient descent to minimize the squared error
Approximat... | Python Code:
#numerical library
import numpy as np
#plot library
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from pprint import pprint
Explanation: Norm approximation on restricted quantized domain
Fast... |
13,887 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Edit this next cell to choose a different country / year report
Step1: These next few conversions don't really work. The PPP data field seems wrong.
Step2: But this one only works if you u... | Python Code:
# BGR_3_2001.json
# BRA_3_2001.json
# MWI_3_2010.23.json
# ECU_3_2014.json
# ARM_3_2010.json
# NGA_3_2009.83.json
# IDN_1_2014.json quite pointed / triangular
# PHL_3_2009.json
# ZAR_3_2012.4.json
# TZA_3_2011.77.json
# VNM_3_2008.json
# MOZ_3_2008.67.json quite rounded
# UZB_3_2003.json
# KIR_3_2006.json ... |
13,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy - multidimensional data arrays
J.R. Johansson (jrjohansson at gmail.com)
The latest version of this IPython notebook lecture is available at http
Step1: Introduction
The numpy packag... | Python Code:
# what is this line all about?!? Answer in lecture 4
%matplotlib inline
import matplotlib.pyplot as plt
Explanation: Numpy - multidimensional data arrays
J.R. Johansson (jrjohansson at gmail.com)
The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/scientific-p... |
13,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Local Development and Validation
This notebook will cover the core parts of the machine learning workflow, running locally within the Google Cloud Datalab environment. Local development and ... | Python Code:
import google.datalab.ml as ml
import json
import math
import matplotlib.pyplot as plot
import mltoolbox.regression.dnn as regression
import numpy as np
import pandas as pd
import os
import seaborn as sns
import sklearn.metrics as metrics
Explanation: Local Development and Validation
This notebook will cov... |
13,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explauto, an open-source Python library to study autonomous exploration in developmental robotics
Explauto is an open-source Python library providing a unified API to design and compare vari... | Python Code:
from explauto.environment import environments
environments.keys()
Explanation: Explauto, an open-source Python library to study autonomous exploration in developmental robotics
Explauto is an open-source Python library providing a unified API to design and compare various exploration strategies driving var... |
13,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step2: IP ClockDivider
Non SoC Test | Python Code:
#This notebook also uses the `(some) LaTeX environments for Jupyter`
#https://github.com/ProfFan/latex_envs wich is part of the
#jupyter_contrib_nbextensions package
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
fr... |
13,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolate bad channels for MEG/EEG channels
This example shows how to interpolate bad MEG/EEG channels
Using spherical splines from
Step1: Compute interpolation (also works with Raw and ... | Python Code:
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Mainak Jas <mainak.jas@telecom-paristech.fr>
#
# License: BSD-3-Clause
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
meg_path = data_path / 'MEG' / 'sample'
fname = meg_path / 'sample_audvis-ave.fi... |
13,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BSTRINGS COMPOUNDING
Step1: Atomic String as an Integral of Atomic Function (introduced in 2017 by Prof S.Eremenko)
Step2: Atomic String, Atomic Function and Atomic Function Derivative plo... | Python Code:
import numpy as np
import pylab as pl
pl.rcParams["figure.figsize"] = 9,6
def BString1(x: float) -> float:
res = 0.5 * np.sin(2.* np.pi * x/2) ###x
if x > 0.5:
res = 0.5
if x < -0.5:
res = -0.5
return res
############### One String Pulse with width, shift and scale #########... |
13,894 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to implement this loss function in TensorFlow using the Keras losses module
| Python Code::
import tensorflow as tf
from tensorflow.keras.losses import MeanAbsoluteError
y_true = [1., 0.]
y_pred = [2., 3.]
mae_loss = MeanAbsoluteError()
loss = mae_loss(y_true, y_pred).numpy()
|
13,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
for Loops
A for loop acts as an iterator in Python, it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can ietrate over include... | Python Code:
# We'll learn how to automate this sort of list in the next lecture
l = [1,2,3,4,5,6,7,8,9,10]
for num in l:
print num
Explanation: for Loops
A for loop acts as an iterator in Python, it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can i... |
13,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: In this exercise we will decode orientation using data collected for the Cognitive Neuroscience module in 2017. The subject performed a task that manipulated whether attention was pl... | Python Code:
import os,json,glob,pickle
import numpy,pandas
import nibabel
import sklearn.multiclass
from sklearn.svm import SVC
import sklearn.metrics
import sklearn.model_selection
import sklearn.preprocessing
import scipy.stats,scipy.io
import random
import seaborn
%matplotlib inline
import matplotlib.pyplot as plt... |
13,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
Full Artificial Neural Network Code Along - CLASSIFICATION
In th... | Python Code:
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: <img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
Full Artificial Neural Network Code Along -... |
13,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Title
Notebook orignially contributed by
Step2: {Put all your imports and installs up into a setup section.}
Notes
For general instructions on... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
13,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 10
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Least squares
One more time, let's load up the NSFG data.
Step2: The following function computes the intercept a... | Python Code:
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + local)
download("https://github.com/AllenDowney/ThinkStats2/raw/master... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.