Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
10,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Planar Point Patterns in PySAL
Author
Step1: Creating Point Patterns
From lists
We can build a point pattern by using Python lists of coordinate pairs $(s_0, s_1,\ldots, s_m)$ as follows
St... | Python Code:
import pysal.lib as ps
import numpy as np
from pysal.explore.pointpats import PointPattern
Explanation: Planar Point Patterns in PySAL
Author: Serge Rey sjsrey@gmail.com and Wei Kang weikang9&#... |
10,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Data Science, CS 5963 / Math 3900
Lecture 3
Step1: Bernoulli Distribution
The Bernoulli distribution, named after Jacob Bernoulli, is the probability distribution of a rando... | Python Code:
import scipy as sc
from scipy.stats import bernoulli
from scipy.stats import binom
from scipy.stats import norm
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10, 6)
Explanation: Introduction to Data Science, CS 5963 / Math 3900
Lecture 3: Hypothesis Testing I
In thi... |
10,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-3', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: UHH
Source ID: SANDBOX-3
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
10,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Printing color
https
Step1: Insults package
Step2: Identifying quotation marks
https | Python Code:
print("\x1b[31m\"red\"\x1b[0m")
print('\x1b[1;31m'+'Hello world'+'\x1b[0m')
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')
print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
pr... |
10,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mathematical method to let poppy vertical
When you want to move the motors of the leg, you can not do whatever you want, because Poppy can fall if it is not balance.
So a very simple way to ... | Python Code:
%pylab inline
from math import *
class leg_angle:
def __init__(self,knee=0):
# different length of poppy in cm
self.upper_body = 40.0
self.shin = 18.0
self.thigh = 18.0
# the angle of the knee
self.knee = radians(knee)
gamma = radians(180 - knee)
... |
10,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
提升算法
提升算法的核心不再是投票,而是迭代.通过一轮一轮的优化权重来做到提升准确率的作用
提升算法(Boosting)虽然表面上看也是对训练数据的扰动(重采样/权值调整),但是Boosting的理论保证了其本质上是一个优化算法.集成分类器整体具有一个优化目标,即Boosting的训练过程最终可以使集成分类器收敛到最优贝叶斯决策,因此降低了bias(提高了准确度),而这个性质是... | Python Code:
import requests
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder,StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report
from sklearn.ensemble import AdaBoostClassifier
Explanati... |
10,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 1
Step1: Load house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Split data into training and testing
... | Python Code:
import graphlab
Explanation: Regression Week 1: Simple Linear Regression
In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:
* Use graphlab SArray and SFrame functions to compute important summary statistics
* Write a... |
10,607 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Importing the necessary libraries required for Matrix Factorization using ALS
| Python Code::
import numpy as np
from pyspark.ml.recommendation import ALS
|
10,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Date Data With Gap In Values
Step2: Interpolate Missing Values
Step3: Forward-fill Missing Values
Step4: Backfill Missing Values
Step5: Interpolate Missing Values Bu... | Python Code:
# Load libraries
import pandas as pd
import numpy as np
Explanation: Title: Handling Missing Values In Time Series
Slug: handling_missing_values_in_time_series
Summary: How to handle the missing values in time series in pandas for machine learning in Python.
Date: 2017-09-11 12:00
Category: Machine Lear... |
10,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In the tutorial, you learned about different ways of measuring fairness of a machine learning model. In this exercise, you'll train a few models to approve (or deny) credit card application... | Python Code:
# Set up feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.ethics.ex4 import *
import pandas as pd
from sklearn.model_selection import train_test_split
# Load the data, separate features from target
data = pd.read_csv("../input/synthetic-credit-card-approval/syntheti... |
10,610 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resonant excitation
We want to study the behaviour of an undercritically damped SDOF system when it is
subjected to a harmonic force $p(t) = p_o \sin\omega_nt$, i.e., when the excitation fre... | Python Code:
def x_2z_over_dst(z):
w = 2*pi
# beta = 1, wn =w
wd = w*sqrt(1-z*z)
# Clough Penzien p. 43
A = z/sqrt(1-z*z)
def f(t):
return (cos(wd*t)+A*sin(wd*t))*exp(-z*w*t)-cos(w*t)
return pl.vectorize(f)
Explanation: Resonant excitation
We want to study the behaviour of an undercr... |
10,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setting the hierarchy in DisMod-MR
The goal of this document is to demonstrate how to set the spatial hierarchy for the random effects in DisMod-MR.
The examples are based on a spatial hiera... | Python Code:
import dismod_mr, numpy as np, pandas as pd
df = pd.read_csv('hierarchy.csv')
df.head()
Explanation: Setting the hierarchy in DisMod-MR
The goal of this document is to demonstrate how to set the spatial hierarchy for the random effects in DisMod-MR.
The examples are based on a spatial hierarchy of Japan, p... |
10,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We covered a lot of information today and I'd like you to practice developing classification trees on your own. For each exercise, work through the problem, determine the result, and provide... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn import datasets
from sklearn import tree
from sklearn.cross_validation import train_test_split
from pandas.tools.plotting import scatter_matrix
Explanation: We covered a lot of information today and I'd l... |
10,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p style="text-align
Step1: Player and odds data from 2010-2016 has beeen matched and stored. Retrieve, merge, and rename.
Step5: Get additional training data. We'll include data from 20... | Python Code:
import sqlalchemy # pandas-mysql interface library
import sqlalchemy.exc # exception handling
from sqlalchemy import create_engine # needed to define db interface
import sys # for defining behavior under errors
import numpy as np # numerical libraries
import scipy as sp
import pandas as pd # for data an... |
10,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"Third" Light
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to updat... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: "Third" Light
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
%matplotlib inline
impor... |
10,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 3
Step2: Problem 1
You start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map).
The toboggan can only follow a few speci... | Python Code:
input_f = './input.txt'
Explanation: Day 3
End of explanation
def find_trees(input_f, move_right, move_down):
Find the trees in the path
trees = 0
pointer = 0
number_of_columns = 0
with open(input_f, 'r') as fd:
for row, line in enumerate(fd, 0):
line... |
10,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Databaker is an Open Source Python library for converting semi-structured spreadsheets into computer-friendly datatables. The resulting data can be stored into Pandas data tabl... | Python Code:
from databaker.framework import *
tab = loadxlstabs("example1.xls", "beatles", verbose=False)[0]
savepreviewhtml(tab, verbose=False)
Explanation: Introduction
Databaker is an Open Source Python library for converting semi-structured spreadsheets into computer-friendly datatables. The resulting data can be... |
10,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Utilities
The file utils.py contains some usefull stuff which is used throughout all notebooks in this site.
First of all it includes the initialization of all constants and variables for th... | Python Code:
# import the mnist class
from mnist import MNIST
# init with the 'data' dir
mndata = MNIST('./data')
# Load data
mndata.load_training()
mndata.load_testing()
# The number of pixels per side of all images
img_side = 28
# Each input is a raw vector.
# The number of units of the network
# corresponds t... |
10,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coastline Evolution Model
The Coastline Evolution Model (CEM) addresses predominately sandy, wave-dominated coastlines on time-scales ranging from years to millenia and on spatial scales ran... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
#Some magic that allows us to view images within the notebook.
%matplotlib inline
Explanation: Coastline Evolution Model
The Coastline Evolution Model (CEM) addresses predominately sandy, wave-dominated coastlines on time-scales ranging from years to mille... |
10,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" align="left"/>
<img src="images/inf.png" alt="" align="right"/>
</header>
<br/><br/><br/><br/><br/>
IWI131
Programaci... | Python Code:
def digitos_faltantes(numero):
digitos_presentes = set(list(str(numero)))
digitos_todos = set(map(str, range(10)))
digitos_que_faltan = digitos_todos - digitos_presentes
digitos_que_faltan = list(digitos_que_faltan)
digitos_que_faltan.sort()
return "".join(digitos_que_faltan)
def es... |
10,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
10,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Latent Dirichlet Allocation for Text Data
In this assignment you will
apply standard preprocessing techniques on Wikipedia text data
use GraphLab Create to fit a Latent Dirichlet allocation ... | Python Code:
import graphlab as gl
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
assert (StrictVersion(gl.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'
# import wiki data
wik... |
10,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load image
Step2: Calculate Mean Color Of Each Color Channel
Step3: Show Values
Step4: View Mean Image Colors | Python Code:
# Load image
import cv2
import numpy as np
from matplotlib import pyplot as plt
Explanation: Title: Using Mean Color As A Feature
Slug: using_mean_color_as_a_feature
Summary: How to use the mean color of an image as a feature using OpenCV in Python with the Shi-Tomasi Corner Detector.
Date: 2017-09-11 1... |
10,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>MEME Wrapper Example</h1>
Step1: <h3>E-value of each motif</h3>
Step2: <h2>fit_predict() and fit_transform() example</h2>
Step3: <h3>Print motives as lists</h3>
Step4: <h3>Display Se... | Python Code:
# Meme().display_meme_help()
from eden.util import configure_logging
import logging
configure_logging(logging.getLogger(),verbosity=2)
from utilities import Weblogo
wl = Weblogo(color_scheme='classic')
meme1 = Meme(alphabet="dna", # {ACGT}
gap_in_alphabet=False,
mod="anr", ... |
10,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Boston Housing Dataset
Step2: Split Data Into Training And Test Set
Step3: Create Dummy Regression Always Predicts The Mean Value Of Target
Step4: Create Dummy Regressi... | Python Code:
# Load libraries
from sklearn.datasets import load_boston
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
Explanation: Title: Create Baseline Regression Model
Slug: create_baseline_regression_model
Summary: How t... |
10,625 | 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', 'thu', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: THU
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties: 85... |
10,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using FastText via Gensim
This tutorial is about using the Gensim wrapper for the FastText library for training FastText models, loading them and performing similarity operations and vector ... | Python Code:
import gensim, os
from gensim.models.wrappers.fasttext import FastText
# Set FastText home to the path to the FastText executable
ft_home = '/home/jayant/Projects/fastText/fasttext'
# Set file names for train and test data
data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.... |
10,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Synthetic Features and Outliers
Learning Objectives
Step1: First, we'll import the California housing data into a pandas DataFrame
Step3: We'll set up our plot_to_image function to convert... | Python Code:
!pip install tensorflow==2.0.0-beta1
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import logging
from packaging import version
from IPython.display import display
pd.options.display.max_rows = 10
pd.options.display.flo... |
10,628 | 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 5
Part 1
Step4: Create reporting function
Step5: Test that the function endpoint works
Step6: Deploy the cloud function
Step7: Try i... | Python Code:
%%bash
wget http://kdd.ics.uci.edu/databases/kddcup99/kddcup.data_10_percent.gz
gunzip kddcup.data_10_percent.gz
BUCKET='cloud-training-demos-ml' # CHANGE
gsutil cp kdd* gs://$BUCKET/
bq mk sparktobq
Explanation: Migrating from Spark to BigQuery via Dataproc -- Part 5
Part 1: The original Spark code, now ... |
10,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(working_with_InferenceData)=
Working with InferenceData
Here we present a collection of common manipulations you can use while working with InferenceData.
Step1: display_expand_data=False ... | Python Code:
import arviz as az
import numpy as np
import xarray as xr
xr.set_options(display_expand_data=False, display_expand_attrs=False);
Explanation: (working_with_InferenceData)=
Working with InferenceData
Here we present a collection of common manipulations you can use while working with InferenceData.
End of ex... |
10,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Seaborn - grids and customization
ToC
- Pairgrids
- lmplot() for scatter and regression per category
- FacetGrid
- Customizing grids
- Fig and font size
Step1: Pairgrids
Pairgrid is si... | Python Code:
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
iris= sns.load_dataset('iris')
iris.head()
Explanation: Seaborn - grids and customization
ToC
- Pairgrids
- lmplot() for scatter and regression per category
- FacetGrid
- Customizing grids
- Fig and font size
End of explanation
g... |
10,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST in Keras with Tensorboard
This sample trains an "MNIST" handwritten digit
recognition model on a GPU or TPU backend using a Keras
model. Data are handled using the tf.data.Datset API.... | Python Code:
BATCH_SIZE = 64
LEARNING_RATE = 0.02
# GCS bucket for training logs and for saving the trained model
# You can leave this empty for local saving, unless you are using a TPU.
# TPUs do not have access to your local instance and can only write to GCS.
BUCKET="" # a valid bucket name must start with gs://
tra... |
10,632 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a dataframe whose last column is the target and the rest of the columns are the features. | Problem:
import numpy as np
import pandas as pd
data = load_data()
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(data.iloc[:, :-1], data.iloc[:, -1], test_size=0.2,
random_state=42) |
10,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stellar Classification
Background
The
Harvard Spectral Classification system for stars
classifies stars based on their spectral type - where the type of a star is designated as a letter tha... | Python Code:
# These are your stellar temperatures, you're welcome!
temperatures = [5809, 16589, 4698, 1869, 37809, 8634]
Explanation: Stellar Classification
Background
The
Harvard Spectral Classification system for stars
classifies stars based on their spectral type - where the type of a star is designated as a lette... |
10,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This "flow downslope" example involves four sub-directories, layer, rho, sigma and z, in which the model is running in one of four coordinate configurations. To use this notebook it is assu... | Python Code:
%pylab inline
import scipy.io.netcdf
Explanation: This "flow downslope" example involves four sub-directories, layer, rho, sigma and z, in which the model is running in one of four coordinate configurations. To use this notebook it is assumed you have run each of those experiments in place and have kept t... |
10,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this notebook, we use the Bluemix CLI tools to create a new IBM Analytics Engine instance that is configured to use IBM Cloud Object Storage (IBM COS).
Load utility library a... | Python Code:
import sys
sys.path.append("./modules")
import iae_examples
Explanation: Introduction
In this notebook, we use the Bluemix CLI tools to create a new IBM Analytics Engine instance that is configured to use IBM Cloud Object Storage (IBM COS).
Load utility library and set notebook width
To prevent this notebo... |
10,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sea Level Rise in New York City
Data Bootcamp Final Project (Spring 2016)
by Daniel Jung (dmj307@stern.nyu.edu)
About This Project
The levels of ocean surfaces (henceforth referred to as t... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Explanation: Sea Level Rise in New York City
Data Bootcamp Final Project (Spring 2016)
by Daniel Jung (dmj307@stern.nyu.edu)
About This Project
The levels of ocean surfaces (henceforth referred to as the 'sea level'... |
10,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
syncID
Step1: Again, let's get the basic bird count data for June 2018. We read the data file to a dataframe, then check the columns' names and data types.
Step2: Notice the 'namedLocation... | Python Code:
import requests
import json
import pandas as pd
#Define API call componenets
SERVER = 'http://data.neonscience.org/api/v0/'
SITECODE = 'TEAK'
PRODUCTCODE = 'DP1.10003.001'
Explanation: syncID:
title: "Querying Location Data with NEON API and Python"
description: "Querying the 'locations/' NEON API endpoin... |
10,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 7
Step1: Part 1
Step2: Part 2 | Python Code:
with open("input/day7.txt", "r") as f:
inputLines = tuple(line.strip() for line in f)
import re
Explanation: Day 7: Internet Protocol Version 7
End of explanation
def isABBA(text):
# Use a negative lookahead assertion to avoid matching four equal characters.
return re.search(r"(.)(?!\1)(.)\2\1"... |
10,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Collection
Step1: Ordinal Genres
Below, we make the genres ordinal to fit in the random forest classifiers. We add a new column to our dataframe to do so, write a function to populate ... | Python Code:
import pandas as pd
from os import path
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier
import sklearn
# Edit path if need be (shouldn't need to b/c we all have the same folder structure)
CSV_PATH_1 = '../Videos/all_data'
CSV_PATH_2 =... |
10,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back
Asynchronous Widgets
This notebook covers two scenarios where we'd like widget-related code to run without blocking the kernel from acting on other execution requests
Step1: We... | Python Code:
%gui asyncio
Explanation: Index - Back
Asynchronous Widgets
This notebook covers two scenarios where we'd like widget-related code to run without blocking the kernel from acting on other execution requests:
Pausing code to wait for user interaction with a widget in the frontend
Updating a widget in the bac... |
10,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DICS for power mapping
In this tutorial, we're going to simulate two signals originating from two
locations on the cortex. These signals will be sine waves, so we'll be looking
at oscillator... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
Explanation: DICS for power mapping
In this tutorial, we're going to simulate two signals originating from two
locations on the cortex. These signals will be sine waves, so we'll be looking
at oscillatory activity (as opposed t... |
10,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing Clustering on Dataframe
We load the Dataframe using code found in stackoverflow("http
Step1: We can see that only 6 of the clusters have significant occupancies. So we are probably ... | Python Code:
import scipy.sparse
import numpy as np
import sklearn as skl
import pylab as plt
%matplotlib inline
def load_sparse_csr(filename):
loader = np.load(filename)
return scipy.sparse.csr_matrix(( loader['data'], loader['indices'], loader['indptr']),
shape = loader['shape'])
Dat... |
10,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
High-performance Simulation with Kubernetes
This tutorial will describe how to set up high-performance simulation using a
TFF runtime running on Kubernetes. The model is the same as in the p... | Python Code:
#@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
Explanation: High-performance Simulation with Kubernetes
This tutorial will describe how to set up high-performance simulation using a
TFF runtime r... |
10,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Analytics Demo
In this demo we will showcase the powerful capabilities of the Data Ninja services by contructing a Text Analytics pipeline from scratch. By combining open source tools a... | Python Code:
from bs4 import BeautifulSoup
import requests
# Sites to exclude from our trending news URL collection
exclusions = ['google.com','youtube.com','wikipedia.org','blogspot.com']
prefix = 'http://'
def include_url(url):
for excl in exclusions:
if url.find(excl) > 0:
return False
re... |
10,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Introduction and Foundations
Project
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the shi... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the datas... |
10,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize Raw data
Step1: The visualization module (
Step2: The channels are color coded by channel type. Generally MEG channels are
colored in different shades of blue, whereas EEG channe... | Python Code:
import os.path as op
import mne
data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample')
raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif'),
add_eeg_ref=False)
raw.set_eeg_reference() # set EEG average reference
events = mne.read_events(op.join(dat... |
10,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example, we cluster our alanine dipeptide trajectory using the RMSD distance metric and hierarchical clustering.
Step1: Let's load up our trajectory. This is the trajectory that we ... | Python Code:
from __future__ import print_function
%matplotlib inline
import mdtraj as md
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy
from scipy.spatial.distance import squareform
Explanation: In this example, we cluster our alanine dipeptide trajectory using the RMSD distance metr... |
10,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
===========================================================
Plot single trial activity, grouped by ROI and sorted by RT
===========================================================
This will ... | Python Code:
# Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.event import define_target_events
from mne.channels import make_1020_channel_selections
print(__doc__)
Explanation: ===========================================================
Plot single trial activity... |
10,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch and create geospatial coordinate and indexes.
Install using pip or any other package manag... | Python Code:
import pandas as pd
from sqlalchemy import create_engine
Explanation: This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch and create geospatial coordinate and indexes.
Install using pip or any other package manager pandas, sqlalchemy and pg8000. The later one... |
10,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transformada de Fourier con Sympy
En este notebook usaremos el módulo de matemática simbólica Sympy, que incluye la función fourier_transform.
Primero cargamos el módulo y activamos la opció... | Python Code:
from sympy import *
init_printing()
Explanation: Transformada de Fourier con Sympy
En este notebook usaremos el módulo de matemática simbólica Sympy, que incluye la función fourier_transform.
Primero cargamos el módulo y activamos la opción para que los resultados se despliegen en forma más amigable en el ... |
10,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Manifold Learning
Step2: Let's call the function and visualize the resulting data
Step3: The output is two dimensiona... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
This notebook contains an excerpt from the Python Data Science Handbook by Jake Vande... |
10,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corriger une position en fonction du couple mesuré sur un moteur
Compétences visées par cette activité
Step1: Utilisation des primitives
Step2: Réalisation d'une primitive permettant d'e... | Python Code:
from poppy.creatures import Poppy4dofArmMini
mini_dof = Poppy4dofArmMini(simulator='vrep')
import time
%pylab inline
Explanation: Corriger une position en fonction du couple mesuré sur un moteur
Compétences visées par cette activité :
Mettre en place un asservissement PID lié au couple mesuré sur un moteur... |
10,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This IPython Notebook introduces the use of the openmc.mgxs module to calculate multi-group cross sections for an infinite homogeneous medium. In particular, this Notebook introduces the the... | Python Code:
from IPython.display import Image
Image(filename='images/mgxs.png', width=350)
Explanation: This IPython Notebook introduces the use of the openmc.mgxs module to calculate multi-group cross sections for an infinite homogeneous medium. In particular, this Notebook introduces the the following features:
Gene... |
10,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Seaborn crash course
<img src='https
Step1: Load sample dataset
Seaborn comes with a number of example dataset. Let us load the restaurant tipping dataset
Step2: Distribution plots
One of ... | Python Code:
import seaborn as sns
%matplotlib inline
Explanation: Seaborn crash course
<img src='https://seaborn.pydata.org/_images/hexbin_marginals.png' height="150" width="150">
Seaborn is an amazing data and statistical visualization library that is built using matplotlib. It has good defaults and very easy to use.... |
10,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the SDK, you need to restart the notebook kernel so it can find the packages. You can restart kern... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip ... |
10,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving for current in R-L-C circuit
Step1: RLC circuit is governed by the following formulas
Step2: RLC circuit fed with dc voltage
For a dc voltage case it has a constant value, so its d... | Python Code:
#importing all required modules
#important otherwise pop-up window may not work
%matplotlib inline
import numpy as np
import scipy as sp
from scipy.integrate import odeint, ode, romb, cumtrapz
import matplotlib as mpl
import matplotlib.pyplot as plt
from math import *
import seaborn
from IPython.display i... |
10,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2-Room Spatial Navigation Analyses
This document contains a demonstration of how to analyse and visualize the 2-Room Spatial Navigation data.
Note that this contains parsing and analysis cod... | Python Code:
data_path = r'Z:\Kelsey\2017 Summer RetLu\Virtual_Navigation_Task\v5_2\NavigationTask_Data\Logged_Data'
study_labels = ['PurseCube', 'CrownCube', 'BasketballCube', 'BootCube', 'CloverCube', 'GuitarCube', 'HammerCube', 'LemonCube', 'IceCubeCube', 'BottleCube']
locations = [[8, -8], [-2, -23], [8, -38], [-14... |
10,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the nscore transformation table
Step1: Getting the data ready for work
If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the ... | Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
from matplotlib.patches import Ellipse
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
Explanation: Testing the nscore transformation table
End of explanation
#get the data in gslib format into a panda... |
10,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Structures like these are encoded in "PDB" files
How can we parse a complicted file like this one?
Step1: We can do better by manually parsing the file.
Our test file
Predict what this will... | Python Code:
import pandas as pd
pd.read_table("data/1stn.pdb")
Explanation: Structures like these are encoded in "PDB" files
How can we parse a complicted file like this one?
End of explanation
f = open("test-file.txt")
print(f.readlines())
f.close()
Explanation: We can do better by manually parsing the file.
Our test... |
10,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Short demo of using ipython_memory_usage to diagnose numpy and Pandas RAM usage
Author Ian uses this tool in his Higher Performance Python training (https
Step1: Importing packages uses som... | Python Code:
import ipython_memory_usage
help(ipython_memory_usage) # or ipython_memory_usage?
%ipython_memory_usage_start
Explanation: Short demo of using ipython_memory_usage to diagnose numpy and Pandas RAM usage
Author Ian uses this tool in his Higher Performance Python training (https://ianozsvald.com/training/) a... |
10,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Librería Cashflows
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí para acceder a la últ... | Python Code:
import cashflows as cf
Explanation: Librería Cashflows
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí para acceder a la última versión online
Haga click aquí para ver la última versión online en nbviewer.... |
10,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of Convolution Theorem
Illustrate the discrete convolution theorem.
F indicates Fourier transform operator and F{f} and F{g} are the fourier transform of "f" and "g" so we have... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import sys,os
ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
from numpy.fft import fft2
from numpy.fft imp... |
10,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 5
Step1: This is a list containing the ages of some group of students, and we want to compute the average. How do we compute averages?
We know an average is some total quantity divi... | Python Code:
ages = [21, 22, 19, 19, 22, 21, 22, 31]
Explanation: Lecture 5: Loops
CSCI 1360: Foundations for Informatics and Analytics
Overview and Objectives
In this lecture, we'll go over the basics of looping in Python. By the end of this lecture, you should be able to
Perform basic arithmetic operations using arbi... |
10,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style='background-image
Step1: 2. Coordinate transformation methods
Step2: 3. COMPUTE AKI & RICHARDS SOLUTION
Step3: 4. Plot displacement components | Python Code:
# Please run it before you start the simulation!
import matplotlib.pyplot as plt
from scipy.special import erf
from scipy.integrate import quad
from numpy import sin, cos, arccos, arctan, pi, sign, sqrt
from numpy import vectorize, linspace, asarray, outer, diff, savetxt
# Show the plots in the Notebook.
... |
10,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiscale example in one dimension
This script applies the FEM to a one dimensional example of a multiscale problem. This problem was introduced by
Peterseim in "Variational Multiscale Stab... | Python Code:
import os
import sys
import numpy as np
%matplotlib notebook
import matplotlib.pyplot as plt
from gridlod import util, world, fem
from gridlod.world import World
import femsolverCoarse
Explanation: Multiscale example in one dimension
This script applies the FEM to a one dimensional example of a multiscale ... |
10,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AveragePooling2D
[pooling.AveragePooling2D.0] input 6x6x3, pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last'
Step1: [pooling.AveragePooling2D.1] input 6x6x3, pool... | Python Code:
data_in_shape = (6, 6, 3)
L = AveragePooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(270)
da... |
10,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
10,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1
Prepared by David Kirkby dkirkby@uci.edu on 14-Jan-2016.
Step2: 1.4.2 Code Management with Git
See the links... | Python Code:
%pylab inline
import astroML
print astroML.__version__
Explanation: Chapter 1
Prepared by David Kirkby dkirkby@uci.edu on 14-Jan-2016.
End of explanation
SDSS Spectrum Example
---------------------
Figure 1.2.
An example of an SDSS spec... |
10,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoregressive Distributed Lag (ARDL) models
ARDL Models
Autoregressive Distributed Lag (ARDL) models extend Autoregressive models with lags of explanatory variables. While ARDL models are t... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style("darkgrid")
sns.mpl.rc("figure", figsize=(16, 6))
sns.mpl.rc("font", size=14)
Explanation: Autoregressive Distributed Lag (ARDL) models
ARDL Models
Autoregressive Distributed Lag (ARDL) models extend Autoregressive models with lags ... |
10,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
4. Model Training
This notebook demonstrates how to train a Propensity Model using BigQuery ML.
Requirements
Input features used for training needs to be stored as a BigQuery table. This can... | Python Code:
# Uncomment to install required python modules
# !sh ../utils/setup.sh
# Add custom utils module to Python environment
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
from gps_building_blocks.cloud.utils import bigquery as bigquery_utils
from utils import model
from utils import helpers
Ex... |
10,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bowl
Initial Gaussian hump sends out ripples in a symmetric bowl-shaped pond. Refinment is focused near one edge of the pond.
Create topography files and data files
Step1: Run code in seri... | Python Code:
%run make_topo.py
%run make_data.py
Explanation: Bowl
Initial Gaussian hump sends out ripples in a symmetric bowl-shaped pond. Refinment is focused near one edge of the pond.
Create topography files and data files
End of explanation
!bowl
Explanation: Run code in serial mode (will work, even if code is... |
10,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How the FFT (Fast Fourier Tranform) works in Python and how to use it. A practical guide.
Motivation
I wrote this in order to have a future reference in how to FFT works in Python. Basically... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sampling_rate = 20 # This quantity is on Hertz
step = 1.0 / sampling_rate
Tmax = 20.0
time = np.arange(0, Tmax, step)
N_to_use = 1024 # Should be a power of two.
Explanation: How the FFT (Fast Fourier Tranform) works in Python and ho... |
10,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CI/CD for a Kubeflow pipeline on Vertex AI
Learning Objectives
Step1: Let us make sure that the artifact store exists
Step2: Creating the KFP CLI builder for Vertex AI
Exercise
In the cell... | Python Code:
PROJECT_ID = !(gcloud config get-value project)
PROJECT_ID = PROJECT_ID[0]
REGION = 'us-central1'
ARTIFACT_STORE = f'gs://{PROJECT_ID}-vertex'
Explanation: CI/CD for a Kubeflow pipeline on Vertex AI
Learning Objectives:
1. Learn how to create a custom Cloud Build builder to pilote Vertex AI Pipelines
1. Le... |
10,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas 소개 2
GonsSu24 내용에 이어서 Pandas 라이브러리를 소개한다.
먼저 GongSu24를 임포트 한다.
Step1: 색인(Index) 클래스
Pandas에 정의된 색인(Index) 클래스는 Series와 DataFrame 자료형의 행과 열을 구분하는 이름들의 목록을 저장하는 데에 사용된다.
Series 객체에서 ... | Python Code:
from GongSu24_Pandas_Introduction_1 import *
Explanation: Pandas 소개 2
GonsSu24 내용에 이어서 Pandas 라이브러리를 소개한다.
먼저 GongSu24를 임포트 한다.
End of explanation
s6 = Series(range(3), index=['a', 'b', 'c'])
s6
Explanation: 색인(Index) 클래스
Pandas에 정의된 색인(Index) 클래스는 Series와 DataFrame 자료형의 행과 열을 구분하는 이름들의 목록을 저장하는 데에 사용된다. ... |
10,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ... | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent ... |
10,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train a binary tumor/normal classifier and explain via Shapely values
Train a neural network on TCGA+TARGET+GTEX gene expression to classify tumor vs. normal.
Evalute the model and explain u... | Python Code:
import os
import json
import numpy as np
import pandas as pd
import keras
import matplotlib.pyplot as plt
# fix random seed for reproducibility
np.random.seed(42)
Explanation: Train a binary tumor/normal classifier and explain via Shapely values
Train a neural network on TCGA+TARGET+GTEX gene expression to... |
10,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word Vectors
Word vectors are vectors of real numbers where each data point captures a dimension of the word's meaning.
The word vectors can be used as features in many natural language pro... | Python Code:
import pandas as pd # to read the dataset
data = pd.read_csv('../datasets/capitals.txt', delimiter=' ')
data.columns = ['city1', 'country1', 'city2', 'country2']
# print first and last five elements in the DataFrame
data.head()
data.tail()
data.describe()
Explanation: Word Vectors
Word vectors are vectors ... |
10,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
1. Radio Science using Interferometric Arrays
Previous
Step1: Import section specific modules
Step2: 1.10 The Limits of Single Dish Astronomy
In the previous section ... | 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
1. Radio Science using Interferometric Arrays
Previous: 1.9 A brief introduction to interferometry
Next: 1.11 Modern Interfe... |
10,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regressão Linear Simples
1. Introdução
A regressão linear é um método de predição com mais de 200 anos de idade. A regressão linear simples é um ótimo primeiro algoritmo de aprendizado de má... | Python Code:
# Calculate the mean value of a list of numbers
def mean(values):
return sum(values) / float(len(values))
Explanation: Regressão Linear Simples
1. Introdução
A regressão linear é um método de predição com mais de 200 anos de idade. A regressão linear simples é um ótimo primeiro algoritmo de aprendizado d... |
10,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Deploying and predicting with model </h1>
<h2>Learning Objectives</h2>
<ol>
<li>Create the model using ai-platform CLI commands</li>
<li>Deploy the ML model to production</li>
<... | Python Code:
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.1
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['RE... |
10,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook for Airconics examples
This IPython notebook contains examples for generating and rendering the AirCONICS parametric transonic airliner example using the interactive WebServer from ... | Python Code:
from airconics import LiftingSurface, Engine, Fuselage
import airconics.AirCONICStools as act
from airconics.Addons.WebServer.TornadoWeb import TornadoWebRenderer
from IPython.display import display
Explanation: Notebook for Airconics examples
This IPython notebook contains examples for generating and rend... |
10,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
New functions
These are recently written functions that have not made it into the main documentation
Python Lesson
Step1: When things go wrong in your eppy script, you get "Errors and Excep... | Python Code:
# you would normaly install eppy by doing
# python setup.py install
# or
# pip install eppy
# or
# easy_install eppy
# if you have not done so, uncomment the following three lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnameto_eppy)
Explanation: New functions
T... |
10,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'></a>
Frequency Response Functions (FRFs) plots
This notebook is about frequency response functions (FRFs) and the various ways they can be plotted.
Table of contents
Preamble
Dyn... | Python Code:
from __future__ import division, print_function
import sys
import numpy as np
import scipy as sp
import matplotlib as mpl
print('System: {}'.format(sys.version))
print('numpy version: {}'.format(np.__version__))
print('scipy version: {}'.format(sp.__version__))
print('matplotlib version: {}'.format(mpl.__v... |
10,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN) Usando Python </h1>
<h3 align="center"> Professor Fernando Vieira da Silva MSc.</h3>
<h2> Técnicas para Pré-Process... | Python Code:
import nltk
import numpy as np
from nltk.tokenize import sent_tokenize
hamlet_raw = nltk.corpus.gutenberg.raw('shakespeare-hamlet.txt')
sents = sent_tokenize(hamlet_raw)
hamlet_np = np.array(sents)
print(hamlet_np.shape)
Explanation: <h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN... |
10,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: 1. Load a shapefile that represents the river network
First, we need to create a Landlab NetworkModelGrid to represent the river network. Each link on the grid represen... | Python Code:
import warnings
warnings.filterwarnings("ignore")
import os
import pathlib
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
from landlab.grid.network import Netwo... |
10,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
lesson1
Step1: Finetuning and Training
Step2: Use a pretrained VGG model with our Vgg16 class
Step4: The original pre-trained Vgg16 class classifies images into one of the 1000 categories... | Python Code:
# make some Python3 functions available on Python2
from __future__ import division, print_function
import sys
print(sys.version_info)
import theano
print(theano.__version__)
import keras
print(keras.__version__)
# FloydHub: check data
%ls /input/dogscats/
# check current directory
%pwd
%ls
# see some files... |
10,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fundamentos de Python 3 en Jupyter
<br>
El lenguaje de programación Python
Step1: <br>
add_numbers es una función que toma dos números y los suma.
Step2: <br>
add_numbers puede actualizars... | Python Code:
x = 20
y = 5
print(x+y)
Explanation: Fundamentos de Python 3 en Jupyter
<br>
El lenguaje de programación Python: Funciones
End of explanation
def add_numbers(x, y):
return x + y
add_numbers(1, 2)
Explanation: <br>
add_numbers es una función que toma dos números y los suma.
End of explanation
def add_... |
10,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Oscillators
This example shows how to generate different signals using the Oscillator module. This module integrates basic structures that implements a simple interface compatible with the ... | Python Code:
import pedsp.oscillator as oscillator
import pedsp.algorithm as algorithm
import matplotlib.pyplot as plt
import numpy as np
amplitude = 1.;
sample_rate = 8000;
frequency = 5;
duration_secs = 2;
samples = int(duration_secs * sample_rate);
duty = 0.5;
square = oscillator.Square(amp=amplitude, sr=sample_rat... |
10,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises
Simple reading
The file ../data/coordinates.txt contains list of (x, y) value pairs.
Read the values into two lists x and y.
Step1: Nontrivial reading and conversion
The file ../d... | Python Code:
xs = []
ys = []
with open("../data/coordinates.txt", "r") as f:
for line in f:
line = line.split()
xs.append(float(line[0]))
ys.append(float(line[1]))
print(xs)
print(ys)
Explanation: Exercises
Simple reading
The file ../data/coordinates.txt contains list of (x, y) value pairs.
... |
10,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Effect Size
Examples and exercises for a tutorial on statistical inference.
Copyright 2015 Allen Downey
License
Step1: To explore statistics that quantify effect size, we'll look at the dif... | Python Code:
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from IPython.html.widgets import interact, fixed
from IPython.html import widgets
# seed the random number generator so we all get the same results
numpy.random.seed(17)
# some nice colors fro... |
10,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="center">
<a href="https
Step1: Simple ConvNet
Step2: Reasons to prefer new implementation
Step3: Super-resolution
<!-- minified https
Step4: Here is the difference
Step5:... | Python Code:
#right
# start from importing some stuff
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from einops import rearrange, reduce, asnumpy, parse_shape
from einops.layers.torch import Rearrange, Reduce
def initialize(model):
for p in model.parameters():
... |
10,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scalable Kalman filtering for Temporal-Spatial Analysis
Seismic monitoring of CO$_2$
State estimation
Time-series data
Methodology
Kalman filter
Scalability
Result
Visit my GitHub page!
Trac... | Python Code:
from IPython.html.widgets import interact, interactive, fixed
from IPython.html.widgets import FloatSlider
from CO2simulation import CO2simulation
def plot_CO2plume(time):
import param as param
CO2 = CO2simulation(param)
x = CO2.extract_state(int(time/3))
data = CO2.extract_data(int(time/3)... |
10,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Нормализация методом Маши
Step1: Данные для смеси 4 кишечных палочек в реальной пропорции. Выравнивали на референс не из данных.
Step2: Низкопокрытые образцы
А что, если нам мешают образцы... | Python Code:
def normalize(M):
M_norm = np.full_like(M, 0)
for i in range(np.shape(M)[0]):
rev = 1 - M[i, :]
if np.dot(M[i, :], M[i, :]) > np.dot(rev, rev):
M_norm[i, :] = rev
else:
M_norm[i, :] = M[i, :]
return M_norm
Explanation: Нормализация методом Маши:
E... |
10,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 2)
Step1: Eulerian Cycles
Before we look at different network types, let us reflect on the distant roots of network ... | Python Code:
from networkit import *
%matplotlib inline
cd ~/Documents/workspace/NetworKit
G = readGraph("input/PGPgiantcompo.graph", Format.METIS)
Explanation: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 2)
End of explanation
# 2-2) and 2-3) Decide whether graph is Eulerian or not
Explanat... |
10,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading utility
Add
Step1: Generation/rendering timing
~$0.189$ seconds per example/.aiff.
18.9s for 100
Step2: Feature extraction timing
~$0.88$ seconds per example/.aiff.
1m 28s for 100
... | Python Code:
dir_list = os.listdir(path=this_dir)
_pickle_path = os.path.join(this_dir, "df.p")
if "df.p" in dir_list:
#_pickle_path = os.path.join(this_dir, "df.p")
_old_df = pd.read_pickle(_pickle_path)
_pickle_dir = make_out_dir(this_dir, "pickle_files")
dt_identifier = datetime.now().strftime("df-%Y... |
10,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Timestamps are contained in the Space Packet secondary header time code field. They are encoded as big-endian 32-bit integers counting the number of seconds elapsed since the J2000 epoch (20... | Python Code:
def timestamps(packets):
epoch = np.datetime64('2000-01-01T12:00:00')
t = np.array([struct.unpack('>I', p[ccsds.SpacePacketPrimaryHeader.sizeof():][:4])[0]
for p in packets], 'uint32')
return epoch + t * np.timedelta64(1, 's')
def load_frames(path):
frame_size = 223 * 5 - ... |
10,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
10,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
I'm Wil Langford. I like math, Python, and games.
me@github
This talk is located in my DecoratorsTalk2015 repository at
Step2: function
Step3: function object
Step4: Uh-oh...
Step6... | Python Code:
global PASSWORD
PASSWORD = "Guild o' Code"
Explanation: Intro
I'm Wil Langford. I like math, Python, and games.
me@github
This talk is located in my DecoratorsTalk2015 repository at:
https://github.com/wil-langford/DecoratorsTalk2015
(or http://goo.gl/AAJ7U0 for short)
To prepare for the talk, please clon... |
10,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<h1>Introduction to Data Analysis with Python</h1>
<br>
<h3>Dr. Thomas Wiecki</h3>
<br>
<h3>Lead Data Scientist</h3>
<img width=40% src="http
Step1: Lists
Step2: Dictionaries
Step... | Python Code:
3 * 4
Explanation: <center>
<h1>Introduction to Data Analysis with Python</h1>
<br>
<h3>Dr. Thomas Wiecki</h3>
<br>
<h3>Lead Data Scientist</h3>
<img width=40% src="http://i2.wp.com/stuffled.com/wp-content/uploads/2014/09/Quantopian-Logo-EPS-vector-image.png?resize=1020%2C680">
</center>
<img src="http://c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.