Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
12,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rossiter-McLaughlin Effect
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't ... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
%matplotlib inline
Explanation: Rossiter-McLaughlin Effect
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 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 expl... |
12,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectrum Continuum Normalization
Aim
Step1: The obeservatios were originally automatically continuum normalized in the iraf extraction pipeline.
I believe the continuum is not quite at 1 h... | Python Code:
import copy
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
% matplotlib inline
#%matplotlib auto
Explanation: Spectrum Continuum Normalization
Aim:
To perform Chi^2 comparision between PHOENIX ACES spectra and my CRIRES observations.
Problem:
The nomalization of the observed... |
12,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
数据结构的内置方法
这一节介绍常用的pandas数据结构内置方法。很重要的一节。
创建本节要用到的数据结构。
Step1: Head() Tail()
想要预览Series或DataFrame对象,可以使用head()和tail()方法。默认显示5行数据,你也可以自己设置显示的行数。
Step2: 属性和 ndarray
pandas对象有很多属性,你可以通过这些属性访问数... | Python Code:
import numpy as np
import pandas as pd
index = pd.date_range('1/1/2000', periods=8)
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=['A', 'B', 'C'])
wp = pd.Panel(np.random.randn(2,5,4), items=['Item1', 'Item2'], major_axis=p... |
12,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Systematic Approach to Visualizing Data
Exploring a Telecom Customer Churn Dataset
TO DO
- Nothing so far.
Acknowlegements
- Thanks to David Wihl for fixing a plotting error.
Introduction
... | Python Code:
# We keep plotting simple and use common packages and defaults
import matplotlib.pyplot as plt
import seaborn as sns
# Set the aesthetics for Seaborn visuals
sns.set(context='notebook',
style='whitegrid',
palette='deep',
font='sans-serif',
font_scale=1.3,
color_... |
12,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Simple Harmonic Oscillator
Here we will expand on the harmonic oscillator first shown in the getting started script. I'll walk you through some of the features of desolver and hopefully ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import desolver as de
import desolver.backend as D
D.set_float_fmt('float64')
Explanation: The Simple Harmonic Oscillator
Here we will expand on the harmonic oscillator first shown in the getting started script. I'll walk you through some of the featu... |
12,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load data
Predict the california average house value
Step1: Model with the recommendation of the cheat-sheet
Based on the Sklearn algorithm cheat-sheet
Step2: Improve the model parametriza... | Python Code:
from sklearn import datasets
all_data = datasets.california_housing.fetch_california_housing()
# Describe dataset
print(all_data.DESCR)
print(all_data.feature_names)
# Print some data lines
print(all_data.data[:10])
print(all_data.target)
#Randomize, normalize and separate train & test
from sklearn.utils i... |
12,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unterricht zur Kammerprüfung
Step1: Sommer_2014
Step2: Frage 1
Erstellen Sie eine SQL-Abfrage, die alle Artikel auflistet, deren Artikelbezeichnungen die Zeichenketten "Schmerzmittel" oder... | Python Code:
%load_ext sql
Explanation: Unterricht zur Kammerprüfung
End of explanation
%sql mysql://steinam:steinam@localhost/sommer_2014
Explanation: Sommer_2014
End of explanation
%%sql
select * from artikel
where Art_Bezeichnung like '%Schmerzmittel%' or
Art_Bezeichnung like '%schmerzmittel%';
Explanation... |
12,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Piecewise Affine Transforms
Step1: We build a PiecewiseAffine by supplying two sets of points and a shared triangle list
Step2: Lets make a random 5000 point PointCloud in the unit square ... | Python Code:
import numpy as np
from menpo.transform import PiecewiseAffine
Explanation: Piecewise Affine Transforms
End of explanation
from menpo.shape import TriMesh, PointCloud
a = np.array([[0, 0], [1, 0], [0, 1], [1, 1],
[-0.5, -0.7], [0.8, -0.4], [0.9, -2.1]])
b = np.array([[0,0], [2, 0], [-1, 3], [... |
12,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a forward operator and display sensitivity maps
Sensitivity maps can be produced from forward operators that
indicate how well different sensor types will be able to detect
neural cur... | Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
trans = data_path + '/MEG/sample/sample_audvis_raw... |
12,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Features selection for multiple linear regression
Following is an example taken from the masterpiece book Introduction to Statistical Learning by Hastie, Witten, Tibhirani, James. It is bas... | Python Code:
import pandas as pd
ad = pd.read_csv("../datasets/advertising.csv", index_col=0)
ad.info()
ad.describe()
ad.head()
%matplotlib inline
import matplotlib.pyplot as plt
plt.scatter(ad.TV, ad.Sales, color='blue', label="TV")
plt.scatter(ad.Radio, ad.Sales, color='green', label='Radio')
plt.scatter(ad.Newspaper... |
12,010 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training Models at Scale with AI Platform
Learning Objectives
Step1: Note
Step2: Create BigQuery tables
If you have not already created a BigQuery dataset for our data, run the following c... | Python Code:
# Use the chown command to change the ownership of repository to user
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Install the Google Cloud BigQuery
!pip install --user google-cloud-bigquery==1.25.0
Explanation: Training Models at Scale with AI Platform
Learning Objectives:
1. Lea... |
12,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Catcher CNN Demo
We first need to import the entire X library by adding the super folder and then importing the right keras libraries
Step1: Setup Game
Here we setup the game and t... | Python Code:
import os, sys
sys.path.append(os.path.join('..'))
import keras.backend as K
K.set_image_dim_ordering('th') # needs to be set since it defaults to tensorflow now
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Flatten
from... |
12,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
List Structures
The concept of a list is similar to oureveryday notion of a list. We read off (access) items on our to-do list, add items, cross off (delete) items, and so forth. We look at ... | Python Code:
["Watermelon"]
list(123)
list("123")
a = []
b = list()
a == b
x = [0,1,2,3,4,5,6]
z = list()
y = list(range(7))
x == y
type(['one', 'two'])
type(['apples' , 50, False])
type([]) # Empty list
# Define a list
# Using list function to create empty list
a = list()
print(type(a))
print(a)
# Using brackets to c... |
12,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modifying yields
This Notebook shows how to modify specific yields without having to re-generate yields table for every case. The modification will alter the input yields internally (within ... | Python Code:
# Import Python modules
import matplotlib.pyplot as plt
# Import NuPyCEE codes
from NuPyCEE import sygma
Explanation: Modifying yields
This Notebook shows how to modify specific yields without having to re-generate yields table for every case. The modification will alter the input yields internally (withi... |
12,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use mozinor for regression
Import the main module
Step1: Prepare the pipeline
(str) filepath
Step2: Now run the pipeline
May take some times
Step3: The class instance, now contains 2 obje... | Python Code:
from mozinor.baboulinet import Baboulinet
Explanation: Use mozinor for regression
Import the main module
End of explanation
cls = Baboulinet(filepath="toto2.csv", y_col="predict", regression=True)
Explanation: Prepare the pipeline
(str) filepath: Give the csv file
(str) y_col: The column to predict
(bool) ... |
12,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
12,016 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PLUMOLOGY
vis
Step1: Reading PLUMED output
We read a file in PLUMED output format
Step2: We can also specify certain columns using regular expressions, and also specify the stepping
Step3:... | Python Code:
from plumology import vis, util, io
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: PLUMOLOGY
vis: Visualization and plotting functions
util: Various utilities and calculation functions
io: Functions to read certain output files and an HDF interface
En... |
12,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
imports needed
What library am I using?
http
Step1: noteStore
http
Step2: my .__MASTER note__ is actually pretty complex....so parsing it and adding to it will take some effort. But let's... | Python Code:
import settings
from evernote.api.client import EvernoteClient
dev_token = settings.authToken
client = EvernoteClient(token=dev_token, sandbox=False)
userStore = client.get_user_store()
user = userStore.getUser()
print user.username
import EvernoteWebUtil as ewu
ewu.init(settings.authToken)
ewu.user.userna... |
12,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectrum Plugins
The SpectrumLike plugin is designed to handle binned photon/particle spectra. It comes in three basic classes
Step1: We will construct a simulated spectrum over the energy ... | Python Code:
from threeML import *
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
Explanation: Spectrum Plugins
The SpectrumLike plugin is designed to handle binned photon/particle spectra. It comes in three basic classes:
SpectrumLike: Generic binned spectral
DispersionSpectrumLike: Generic bi... |
12,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Linear Spatial Autocorrelation Model
The two methodologies under study (i.e. Meta-analysis and distributed networks) share the assumption that the observations are independent betwee... | Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
import django
django.setup()
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
## Use the ggplot style
plt.style.use('ggplot')
## check the matern
import scipy.special as special
#def MaternVariogr... |
12,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
In this notebook, I'll try converting radio images into useful features using a simple convolutional neural network in Keras. The best kinds of CNN to use are a... | Python Code:
import collections
import io
from pprint import pprint
import sqlite3
import sys
import warnings
import astropy.io.votable
import astropy.wcs
import matplotlib.pyplot
import numpy
import requests
import requests_cache
import sklearn.cross_validation
%matplotlib inline
sys.path.insert(1, '..')
import crowda... |
12,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 14
Step1: Sometimes you see double dots at the beginning of the file path; this means 'the parent of the current directory'. When writing a file path, you can use the following
Step... | Python Code:
filename = "../Data/Charlie/charlie.txt"
# The double dots mean 'go up one level in the directory tree'.
Explanation: Chapter 14: Reading and writing text files
We use some materials from this other Python course.
In this chapter, you will learn how to read data from files, do some analysis, and write t... |
12,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute source power using DICS beamfomer
Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ filter from
single-trial activity to estimate source power across a frequency band. This
e... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
# Roman Goj <roman.goj@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import ma... |
12,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AIA Response Function Tests
Step1: The goal of this notebook is to test the wavelength and temperature response function calculations that are currently being developed in SunPy.
Wavelengt... | Python Code:
import os
import sys
import pickle
import numpy as np
import scipy
import matplotlib.pyplot as plt
import ChiantiPy.core as ch
import sunpy.instr.aia as aia
%matplotlib inline
Explanation: AIA Response Function Tests
End of explanation
response = aia.Response(path_to_genx_dir='../ssw_aia_response_data/')
r... |
12,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mie Performance and Jitting
Scott Prahl
Apr 2021
If miepython is not installed, uncomment the following cell (i.e., delete the #) and run (shift-enter)
Step1: Size Parameters
We will use %t... | Python Code:
#!pip install --user miepython
import numpy as np
import matplotlib.pyplot as plt
try:
import miepython.miepython as miepython_jit
import miepython.miepython_nojit as miepython
except ModuleNotFoundError:
print('miepython not installed. To install, uncomment and run the cell above.')
print(... |
12,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Variational Equations With the Chain Rule
For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016).
Variational equations can be used to ca... | Python Code:
import rebound
import numpy as np
Explanation: Using Variational Equations With the Chain Rule
For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016).
Variational equations can be used to calculate derivatives in an $N$-body simulation. More specifically, give... |
12,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q
看一下 mnist 資料
開始 Tensorflow
Step1: Softmax regression
基本上就是用
$ e ^ {W x +b} $ 的比例來計算機率
其中 x 是長度 784 的向量(圖片), W 是 10x784矩陣,加上一個長度為 10 的向量。 算出來的十個數值,依照比例當成我們預估的機率。
Step2: Loss function 的計算... | Python Code:
import tensorflow as tf
from tfdot import tfdot
Explanation: Q
看一下 mnist 資料
開始 Tensorflow
End of explanation
# 輸入的 placeholder
X = tf.placeholder(tf.float32, shape=[None, 784], name="X")
# 權重參數,為了計算方便和一些慣例(行向量及列向量的差異),矩陣乘法的方向和上面解說相反
W = tf.Variable(tf.zeros([784, 10]), name='W')
b = tf.Variable(tf.zeros([1... |
12,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trace Analysis Examples
Idle States Residency Analysis
This notebook shows the features provided by the idle state analysis module. It will be necessary to collect the following events
Step1... | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
%matplotlib inline
import os
# Support to access the remote target
from env import TestEnv
# Support to access cpuidle information from the target
from devlib import *
# Support to configure and run RTApp based workloads
from wlgen import RTA,... |
12,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
+
Word Count Lab
Step2: (1b) Pluralize and test
Let's use a map() transformation to add the letter 's' to each string in the base RDD we just created. We'll define a Python function that ... | Python Code:
wordsList = ['cat', 'elephant', 'rat', 'rat', 'cat']
wordsRDD = sc.parallelize(wordsList, 4)
# Print out the type of wordsRDD
print type(wordsRDD)
Explanation: +
Word Count Lab: Building a word count application
This lab will build on the techniques covered in the Spark tutorial to develop a simple word c... |
12,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goulib.polynomial
polynomial and piecewise defined functions
Step1: Polynomial
a Polynomial is an Expr defined by factors and with some more methods
Step2: Motion
"motion laws" are functio... | Python Code:
from Goulib.notebook import *
from Goulib.polynomial import *
from Goulib import itertools2, plot
Explanation: Goulib.polynomial
polynomial and piecewise defined functions
End of explanation
p1=Polynomial([-1,1,3]) # inited from coefficients in ascending power order
p1 # Latex output by default
p2=Polynomi... |
12,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hands-on!
Nessa prática, sugerimos alguns pequenos exemplos para você implementar sobre o Spark.
Logistic Regression com Cross-Validation
No exercício LogisticRegression foi utilizado TrainV... | Python Code:
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import RegressionEvaluator, MulticlassClassificationEvaluator
from pyspark.ml import Pipeline
from pyspark.mllib.regression import LabeledPoint
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import StringInde... |
12,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
1. Setup
First, Load necessary libs and set up caffe and caffe_root
Step1: Load LabelMap.
Step2: ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Only run this cell once in the active kernel or the files in later cells will not be found
# Make sure that c... |
12,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 26
Step1: find.all() returns a list of strings.
It behaves differently with groups.
Step2: To get the total string, just wrap the total regex in its own group, so you get [(totalst... | Python Code:
import re
phoneRegex = re.compile(r'/d/d/d-/d/d/d-/d/d/d/d')
#phoneRegex.search() # finds first match
#phoneRegex.findall() # finds all matches
Explanation: Lesson 26:
RegEx Character Classes and the .findall() Method
The find.all() method for regex objects finds all matching strings in a text.
End of expl... |
12,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Objects and exceptions
Object-oriented programming is a widespread paradigm that helps programmers create intuitive layers of abstraction. This example notebook is aimed at helping pe... | Python Code:
class Vector2D(object):
Represents a 2-dimensional vector
def __init__(self, x, y):
self.x = x
self.y = y
Explanation: Objects and exceptions
Object-oriented programming is a widespread paradigm that helps programmers create intuitive layers of abstraction. This example noteboo... |
12,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning 2. Convolutional Neural Networks
The dense FFN used before contained 600000 parameters. These are expensive to train!
A picture is not a flat array of numbers, it is a 2D matri... | Python Code:
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
train_images = train_images.astype('float32') / 255
test_images = test_images.re... |
12,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
training an unsupervised VAE with APOGEE DR14 spectra
this notebooke takes you through the building and training of a fairly deep VAE. I have not actually done too much work with DR14, so it... | Python Code:
import numpy as np
import time
import h5py
import keras
import matplotlib.pyplot as plt
import sys
from keras.layers import (Input, Dense, Lambda, Flatten, Reshape, BatchNormalization, Activation,
Dropout, Conv1D, UpSampling1D, MaxPooling1D, ZeroPadding1D, LeakyReLU)
from keras.e... |
12,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stacker-Crane Experiments
The Euclidean Stacker-Crane problem (ESCP) is a generalization of the Euclidean Travelling Salesman Problem. In the ESCP we are given pickup-delivery pairs and aim ... | Python Code:
# Load modules
import sys
from __future__ import print_function
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
import pandas as pd
from pandas import DataFrame
import time
import random
from pqt import PQTDecomposition
from... |
12,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ubiquitous NumPy
I called this notebook ubiquitous numpy as the main goal of this section is to show examples of how much is the impact of NumPy over the Scientific Python Ecosystem.
Later o... | Python Code:
from IPython.core.display import Image, display
display(Image(filename='images/iris_setosa.jpg'))
print("Iris Setosa\n")
display(Image(filename='images/iris_versicolor.jpg'))
print("Iris Versicolor\n")
display(Image(filename='images/iris_virginica.jpg'))
print("Iris Virginica")
Explanation: Ubiquitous NumP... |
12,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weighting functions in the $CO_2$ 15 $\mu m$ absorption band
Below is a plot of radiance (or intensity) (left axis) and brightness temperature (right axis) vs. wavenumber near the main $CO_2... | Python Code:
Image('figures/wallace4_33.png',width=500)
Explanation: Weighting functions in the $CO_2$ 15 $\mu m$ absorption band
Below is a plot of radiance (or intensity) (left axis) and brightness temperature (right axis) vs. wavenumber near the main $CO_2$ absorption band. Wavenumber is defined as $1/\lambda$; the... |
12,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following are the results we've got from online augmentation so far. Some bugs have been fixed by Scott since then so these might be redundant. If they're not redundant then they are ver... | Python Code:
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import holoviews as hl
%load_ext holoviews.ipython
import sklearn.metrics
cd ..
settings = neukrill_net.utils.Settings... |
12,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Оценки тестирования по результатам
Описание
Пусть есть тест с известными правильными ответами и диапазонами ответов на каждый вопрос.
Для определённости возьмём возможные ответы как 0 или 1... | Python Code:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
Explanation: Оценки тестирования по результатам
Описание
Пусть есть тест с известными правильными ответами и диапазонами ответов на каждый вопрос.
Для определённости возьмём возможные ответы как 0 или 1.
Сложность каждого за... |
12,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot of allometrically-scaled mass-specific metabolic rate
Step1: Replicating allometrically-scaled calculated parameters
First attempt
Step2: Second attempt
Based on information on Biot 2... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# This plot shows how mass-specific metabolic rate falls off with body size
x = np.arange(1, 100)
plt.plot(x, x**-.25)
plt.xlabel("body size")
plt.ylabel("metabolic rate")
Explanation: Plot of allometrically-scaled mass-specific metaboli... |
12,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SRTM Product Showcase
Products used
Step1: Define Methods
slope_pct
* dem
Step2: Connect to the datacube
Step3: Set Analysis Region | Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
%matplotlib inline
import datacube
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from scipy.ndimage import convolve
Explanation: SRTM Product Showcase
Products used:
srtm_google (original source)
Dataset from 11... |
12,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Here we will be focusing more on the cnmf part and its main functions <h1>
<img src='docs/img/cnmf1.png'/>
Step1: <h1> Using the workload manager SLURM </h1>
to have an extensive use o... | Python Code:
try:
if __IPYTHON__:
# this is used for debugging purposes only. allows to reload classes when changed
get_ipython().magic(u'load_ext autoreload')
get_ipython().magic(u'autoreload 2')
except NameError:
print('Not IPYTHON')
pass
import sys
import numpy as np
fr... |
12,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back - Next
Widget List
Step1: Numeric widgets
There are many widgets distributed with ipywidgets that are designed to display numeric values. Widgets exist for displaying integers... | Python Code:
import ipywidgets as widgets
Explanation: Index - Back - Next
Widget List
End of explanation
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d'
)
... |
12,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KNOWLEDGE
The knowledge module covers Chapter 19
Step1: CONTENTS
Overview
Current-Best Learning
OVERVIEW
Like the learning module, this chapter focuses on methods for generating a model/hyp... | Python Code:
from knowledge import *
from notebook import pseudocode, psource
Explanation: KNOWLEDGE
The knowledge module covers Chapter 19: Knowledge in Learning from Stuart Russel's and Peter Norvig's book Artificial Intelligence: A Modern Approach.
Execute the cell below to get started.
End of explanation
pseudocode... |
12,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Input File Creation
First let's start with some tools to create input files for a given deployment schedule.
Step3: Simulate
Now let's build some tools to run simulations and extract a GWe ... | Python Code:
import os
import sys
import uuid
import json
import time
import subprocess
from math import ceil
from copy import deepcopy
import numpy as np
import pandas as pd
import cymetric as cym
%matplotlib inline
import matplotlib.pyplot as plt
import george
import dtw
with open('once-through.json') as f:
BASE_... |
12,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Morph volumetric source estimate
This example demonstrates how to morph an individual subject's
Step1: Setup paths
Step2: Compute example data. For reference see ex-inverse-volume.
Load da... | Python Code:
# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD-3-Clause
import os
import nibabel as nib
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.minimum_norm import apply_inverse, read_inverse_operator
from nilearn.plotting import plot_glass_brain
print(__doc__)
Explanatio... |
12,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natural Language Processing with NLTK
Author
Step1: 1. Corpus acquisition.
In these notebooks we will explore some tools for text processing and analysis and two topic modeling algorithms a... | Python Code:
%matplotlib inline
# Required imports
from wikitools import wiki
from wikitools import category
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import gensim
import numpy as np
import lda
import lda.datasets
import matplotlib.pyp... |
12,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2016-09-30
Step2: 1.1 Cross-validation
Question
Step3: Now use this function to compute cross-validated predictions on the data.
Step4: Question Complete the code below to compute the cro... | Python Code:
import numpy as np
%pylab inline
# Load the data
X = np.loadtxt('data/small_Endometrium_Uterus.csv', delimiter=',', skiprows=1, usecols=range(1, 3001))
# Python 2.7 only
y = np.loadtxt('data/small_Endometrium_Uterus.csv', delimiter=',', skiprows=1, usecols=[3001],
converters={3001: lambda ... |
12,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Previous
1.3 保留最后N个元素
问题
在迭代操作或者其他操作的时候,怎样只保留最后有限几个元素的历史记录?
解决方案
保留有限历史记录正是 collections.deque 大显身手的时候。比如,下面的代码在多行上面做简单的文本匹配, 并返回匹配所在行的前 N 行:
``` python
from collections import deque
def sear... | Python Code:
from collections import deque
q = deque(maxlen = 3)
q.append(1)
q.append(2)
q.append(3)
q
q.append(4)
q
q.append(5)
q
Explanation: Previous
1.3 保留最后N个元素
问题
在迭代操作或者其他操作的时候,怎样只保留最后有限几个元素的历史记录?
解决方案
保留有限历史记录正是 collections.deque 大显身手的时候。比如,下面的代码在多行上面做简单的文本匹配, 并返回匹配所在行的前 N 行:
``` python
from collections import ... |
12,051 | 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 ... |
12,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running an MSTIS simulation
Now we will use the initial trajectories we obtained from bootstrapping to run an MSTIS simulation. This will show both how objects can be regenerated from storag... | Python Code:
%matplotlib inline
import openpathsampling as paths
import numpy as np
Explanation: Running an MSTIS simulation
Now we will use the initial trajectories we obtained from bootstrapping to run an MSTIS simulation. This will show both how objects can be regenerated from storage and how regenerated equivalent ... |
12,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monte Carlo Dropout -- Example Notebook
Launch this notebook in Google CoLab
This notebook is a modified fork of the Bayesian MNIST classifier implementation here.
In this notebook, a Bayesi... | Python Code:
! wget https://media.githubusercontent.com/media/rahulremanan/python_tutorial/master/Machine_Vision/07_Bayesian_deep_learning/weights/bayesianLeNet.h5 -O ./bayesianLeNet.h5
Explanation: Monte Carlo Dropout -- Example Notebook
Launch this notebook in Google CoLab
This notebook is a modified fork of the Baye... |
12,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Survival Analysis
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: This chapter introduces "survival analysis", which is a set of statistical methods used to answer... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
12,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro Spacy
Step2: Spacy Documentation
Spacy is an NLP/Computational Linguistics package built from the ground up. It's written in Cython so it's fast!!
Let's check it out. Here's some text... | Python Code:
!pip install spacy nltk
Explanation: Intro Spacy
End of explanation
text = 'Please would you tell me,' said Alice, a little timidly, for she was not quite sure whether it was good manners for her to speak first, 'why your cat grins like that?'
'It's a Cheshire cat,' said the Duchess, 'and that's why. Pig!'... |
12,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning, part3
Step1: Autoencoders properties and usage
Step2: Goal
Step3: Task | Python Code:
from IPython.display import Image
Image(url= "../img/AE.png", width=400, height=400)
Explanation: Deep Learning, part3: Other important examples
Generative models: autoencoders and GANS
Working with tabular data, data integration
Recurrent NN and attention mechanisms
Reinforcement learning
Generative model... |
12,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Context
Often, it isn't possible to get the real data where we applied our analysis. In these cases, we can generate similar dataset that contain similar phenomena based on real data. This n... | Python Code:
from lib.ozapfdis import git_tc
log = git_tc.log_numstat("C:/dev/repos/buschmais-spring-petclinic")
log.head()
log = log[log.file.str.contains(".java")]
log.loc[log.file.str.contains("/jdbc/"), 'type'] = "jdbc"
log.loc[log.file.str.contains("/jpa/"), 'type'] = "jpa"
log.loc[log.type.isna(), 'type'] = "othe... |
12,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análise Exploratória
Esse notebook introduz os conceitos de Análise Exploratória
Para isso utilizaremos a base de dados de Crimes de São Francisco obtidos do site de competições Kaggle.
Es... | Python Code:
import os
import numpy as np
from pyspark import SparkContext
sc = SparkContext()
filename = os.path.join("Data","Aula03","Crime.csv")
CrimeRDD = sc.textFile(filename,8)
header = CrimeRDD.take(1)[0] # o cabeçalho é a primeira linha do arquivo
print "Campos disponíveis: {}".format(header)
Explanation: Análi... |
12,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Phenotype Phase Plane
Phenotype phase planes will show distinct phases of optimal growth with different use of two different substrates. For more information, see Edwards et al.
Cobrapy supp... | Python Code:
%matplotlib inline
from time import time
import cobra.test
from cobra.flux_analysis import calculate_phenotype_phase_plane
model = cobra.test.create_test_model("textbook")
Explanation: Phenotype Phase Plane
Phenotype phase planes will show distinct phases of optimal growth with different use of two differe... |
12,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content and Objectives
Show validity of theorems for generating arbitrary distributions out of uniform distribution
Import
Step1: Exponential out of Uniform
Step2: Gaussian out of Uniform
... | Python Code:
# importing
import numpy as np
from scipy import stats, special
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=True)
matplotlib.rc('figure', figsize=(18, 6) )
Explanation: ... |
12,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run Generic Automated EAS tests
This is a starting-point notebook for running tests from the generic EAS suite in tests/eas/generic.py. The test classes that are imported here provide helper... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import logging
from conf import LisaLogging
LisaLogging.setup()#level=logging.WARNING)
import pandas as pd
from perf_analysis import PerfAnalysis
import trappy
from trappy import ILinePlot
from trappy.stats.grammar import Parser
Explanation: Run Generic... |
12,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining decaying sin wave
Function accepts dictionary of parameters and array of x-points, returns array of y-points. Represents fit model.
Step1: Plotting function for default parameters
... | Python Code:
def decaying_sin(params, x):
amp = params['amp']
phaseshift = params['phase']
freq = params['frequency']
decay = params['decay']
return amp * np.sin(x*freq + phaseshift) * np.exp(-x*x*decay)
Explanation: Defining decaying sin wave
Function accepts dictionary of parameters and array of x... |
12,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating and Using Panel Data Using ArcGIS Defined Location Cubes
Step1: Example
Step2: Open Panel Cube From NetCDF File for Analysis
Step3: Number of Locations and Time Periods
Step4: L... | Python Code:
import os as OS
import arcpy as ARCPY
import SSDataObject as SSDO
import SSPanelObject as SSPO
import SSPanel as PANEL
ARCPY.overwriteOutput = True
Explanation: Creating and Using Panel Data Using ArcGIS Defined Location Cubes
End of explanation
inputFC = r'../data/CA_Counties_Panel.shp'
outputCube = r'../... |
12,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Distance entre deux mots de même longueur et tests unitaires
Calculer une distance entre deux mots n'est pas le plus intuitif des problèmes. Dans ce notebook, on se permet de tâtonner pour f... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Distance entre deux mots de même longueur et tests unitaires
Calculer une distance entre deux mots n'est pas le plus intuitif des problèmes. Dans ce notebook, on se permet de tâtonner pour faire évoluer quelques idées autour du su... |
12,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
Explanation: A Simple Autoencoder
We'll start off by building a simple autoencoder to c... |
12,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training
Define feature function
Input is 3D array and voxelsize. Output is feature vector with rows number equal to pixel number and cols number equal
to number of features.
Step1: Classif... | Python Code:
def externfv(data3d, voxelsize_mm): # scale
f0 = scipy.ndimage.filters.gaussian_filter(data3d, sigma=3).reshape(-1, 1)
f1 = scipy.ndimage.filters.gaussian_filter(data3d, sigma=1).reshape(-1, 1) - f0
fv = np.concatenate([
f0, f1
], 1)
return fv
Explanation: Training
Define... |
12,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source localization with a custom inverse solver
The objective of this example is to show how to plug a custom inverse solver
in MNE in order to facilate empirical comparison with the method... | Python Code:
import numpy as np
from scipy import linalg
import mne
from mne.datasets import sample
from mne.viz import plot_sparse_source_estimates
data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fn... |
12,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Spectral Representations of Natural Images
This notebook will show how to extract the spect... | Python Code:
#@title License
# 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, softw... |
12,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the pyEMMA API
Step1: Now we import a few general packages that we need to start with. The following imports basic numerics and algebra routines (numpy) and plotting routines (matpl... | Python Code:
import pyemma
pyemma.__version__
Explanation: Testing the pyEMMA API
End of explanation
import matplotlib.pylab as plt
import numpy as np
%pylab inline
Explanation: Now we import a few general packages that we need to start with. The following imports basic numerics and algebra routines (numpy) and plottin... |
12,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 3
Step1: Step 1
Step2: The full list of parameters that can be set with the initialization are as follows (all are optional).
| Argument | Defaults | Purpose |
| ------------- | --... | Python Code:
# Import relevant modules
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import corner
import matplotlib.pyplot as plt
from NPTFit import nptfit # module for performing scan
from NPTFit import create_mask as cm # module for creating the mask
from NPTFit import dnds_analysis # modu... |
12,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Locality Sensitive Hashing
Question 1
The edit distance is the minimum number of character insertions and character deletions required to turn one string into another. Compute the edit dista... | Python Code:
from collections import defaultdict
from itertools import combinations
def lcs(a, b):
lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]
for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i+1][j+1] = lengths[i][j] + 1
... |
12,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Here we see tokens combine to form the entities Washington, DC, next May and the Washington Monument
Entity annotations
Doc.ents are token spans with their own set of a... | Python Code:
# Perform standard imports
import spacy
nlp = spacy.load('en_core_web_sm')
# Write a function to display basic entity info:
def show_ents(doc):
if doc.ents:
for ent in doc.ents:
print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))
else:
print('No named e... |
12,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy
NumPy is the fundamental package for scientific computing with Python. The main additions to the standard Python are
New datatype, NumPy array
static, multidimensional
Fast processing ... | Python Code:
import numpy as np
Explanation: NumPy
NumPy is the fundamental package for scientific computing with Python. The main additions to the standard Python are
New datatype, NumPy array
static, multidimensional
Fast processing of arrays
Tools for linear algebra, random numbers, ...
Numpy array
The NumPy array i... |
12,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pivoted Document Length Normalization
Background
In many cases, normalizing the tfidf weights for each term favors weight of terms of the documents with shorter length. The pivoted document ... | Python Code:
#
# Download our dataset
#
import gensim.downloader as api
nws = api.load("20-newsgroups")
#
# Pick texts from relevant newsgroups, split into training and test set.
#
cat1, cat2 = ('sci.electronics', 'sci.space')
#
# X_* contain the actual texts as strings.
# Y_* contain labels, 0 for cat1 (sci.electronic... |
12,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Active Network Management Framework
This notebook stands as a tutorial and as a showcase of the Python package we developped in order to promote the development of computational techniques f... | Python Code:
from ANM import Simulator
from case75 import case75
from numpy.random import RandomState
sim = Simulator(case75(), rng=RandomState(987654321))
Explanation: Active Network Management Framework
This notebook stands as a tutorial and as a showcase of the Python package we developped in order to promote the de... |
12,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q1. Solution
3-shingles for "hello world"
Step1: Q3.
This question involves three different Bloom-filter-like scenarios. Each scenario involves setting to 1 certain bits of a 10-bit array, ... | Python Code:
## Q2 Solution.
def hash(x):
return math.fmod(3 * x + 2, 11)
for i in xrange(1,12):
print hash(i)
Explanation: Q1. Solution
3-shingles for "hello world":
hel, ell, llo, lo_, o_w ,_wo, wor, orl, rld => 9 in total
Q2. Solution
End of explanation
## Q3 Solution.
prob = 1.0 / 10
a = (1 - prob)**4
print... |
12,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Boilerplate
Step1: Sample from the model
This section demonstrates the most basic usage of the package, i.e., sampling from a pre-trained model.
Step2: Create the environment
First, we nee... | Python Code:
import copy
import os
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
import tensorflow as tf
import tensorflow_hub as hub
import spiral.agents.default as default_agent
import spiral.agents.utils as agent_utils
from spiral.environments import fluid
from spiral.environments impo... |
12,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to The QuantConnect Research Page
Refer to this page for documentation https
Step1: Historical Data Requests
We can use the QuantConnect API to make Historical Data Requests. The da... | Python Code:
%matplotlib inline
# Imports
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Jupyter")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from QuantConnect.Data.Custom import *
from QuantConnect.Data.Mar... |
12,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DES Y6 Deep Field Exposures
Step1: 2. User Input
2.1. General User Input
Step2: 2.2. Logical Variables to Indicate which Code Cells to Run
Step3: 2.3. Sky Region Definitions
Step4: 2.4.... | Python Code:
import numpy as np
import pandas as pd
from scipy import interpolate
import glob
import math
import os
import subprocess
import sys
import gc
import glob
import pickle
import easyaccess as ea
#import AlasBabylon
import fitsio
from astropy.io import fits
import astropy.coordinates as coord
from astropy.coor... |
12,080 | Given the following text description, write Python code to implement the functionality described.
Description:
Flatten a multi |
| Python Code:
def flattenList2(head ) :
headcop = head
save =[]
save . append(head )
prev = None
while(len(save ) != 0 ) :
temp = save[- 1 ]
save . pop()
if(temp . next ) :
save . append(temp . next )
if(temp . down ) :
save . append(temp . down )
if(prev != None ) :
prev . next = temp... |
12,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step1: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
import scipy.stats
Explanation: Line with Gaussian noise
Write a function named... |
12,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to jeepr with gprMax data
jeepr is a set of utilities for handling GPR data, especially gprMax models and synthetics, and real data from USRadar instruments.
Step1: Make Scan from a g... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
import jeepr
jeepr.__version__
Explanation: Intro to jeepr with gprMax data
jeepr is a set of utilities for handling GPR data, especially gprMax models and synthetics, and real data from USRadar instruments.
End of explanation
from jeep... |
12,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Distributed Numpy Parsing
Joeri R. Hermans
Departement of Data Science & Knowledge Engineering
Maastricht University, The Netherlands
This notebook will ... | Python Code:
%matplotlib inline
import numpy as np
import os
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql.types import *
from pyspark.sql import Row
from pyspark.storagelevel import StorageLevel
# Use the DataBricks AVRO reader.
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages com.data... |
12,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 2 - Logic, Loops, and Arrays
This iPython notebook covers some of the most important aspects of the Python language that is used daily by real Astronomers and Physicists. Topics will... | Python Code:
#Example conditional statements
x = 1
y = 2
x<y #x is less than y
#x is greater than y
x>y
#x is less-than or equal to y
x<=y
#x is greater-than or equal to y
x>=y
Explanation: Lecture 2 - Logic, Loops, and Arrays
This iPython notebook covers some of the most important aspects of the Python language that i... |
12,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
python async programming
非同步編程在python中最近是越來越受歡迎,在python中有著許多libraries是用來做非同步的,其中之一是asyncio而且這也是讓python在async編程受歡迎的主因,在開始正題前,我們先來理解一些歷史緣由。
在普遍的程式,執行順序都是一行一行執行,每次要繼續往下執行前,都會等著上一行完成,也就是俗稱的Seque... | Python Code:
import time
def n_hello():
for i in range(6):
print(i)
def c_hello():
for i in range(4):
print('in function {}'.format(i))
yield i
def infinit_loop():
num = 0
while True:
num += 1
print(num)
yield
n_hello()
print("=====")
c = c_... |
12,086 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classic Monty Hall Bayesian Network
authors
Step1: Let's create the distributions for the guest and the prize. Note that both distributions are independent of one another.
Step2: Now let's... | Python Code:
import math
from pomegranate import *
Explanation: Classic Monty Hall Bayesian Network
authors:<br>
Jacob Schreiber [<a href="mailto:jmschreiber91@gmail.com">jmschreiber91@gmail.com</a>]<br>
Nicholas Farn [<a href="mailto:nicholasfarn@gmail.com">nicholasfarn@gmail.com</a>]
Lets test out the Bayesian Networ... |
12,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quaternion Series Quantum Mechanics
Step1: Lecture 1
Step2: The first term is a real-valued, with the 3-imaginary vector equal to zero. I think it is bad practice to just pretend the three... | Python Code:
%%capture
%matplotlib inline
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
# To get equations the look like, well, equations, use the following.
from sympy.interactive import printing
printing.init_printing(use_latex=True)
from IPython.display import display
# Tools for manipulating... |
12,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D... | Python Code:
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called... |
12,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estandarizacion de datos de los Anuarios Geoestadísticos de INEGI 2017
1. Introduccion
Parámetros que se obtienen de esta fuente
Step1: 2. Descarga de datos
Cada entidad cuenta con una pági... | Python Code:
descripciones = {
'P0610': 'Ventas de electricidad',
'P0701': 'Longitud total de la red de carreteras del municipio (excluyendo las autopistas)'
}
# Librerias utilizadas
import pandas as pd
import sys
import urllib
import os
import csv
import zipfile
# Configuracion del sistema
print('Python {} on ... |
12,090 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Load the data
As a first step we will load a large dataset using dask. If you have followed the setup instructions you will have downloaded a large CSV containing 12 mi... | Python Code:
import pandas as pd
import holoviews as hv
import dask.dataframe as dd
import datashader as ds
import geoviews as gv
from holoviews.operation.datashader import datashade, aggregate
hv.extension('bokeh')
Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%... |
12,091 | 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... |
12,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'niwa', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-3
Topic: Seaice
Sub-Topics: Dynamics, Thermodynamic... |
12,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting age distributions with respect to genotype groups
Step1: For two of the 5 groups, the Shapiro test p-value is lower than 1e-3, which means that the distributions of these two group... | Python Code:
%matplotlib inline
import pandas as pd
from scipy import stats
from matplotlib import pyplot as plt
data = pd.read_excel('/home/grg/spm/data/covariates.xls')
for i in xrange(5):
x = data[data['apo'] == i]['age'].values
plt.hist(x, bins=20)
print i, 'W:%.4f p:%.4f -'%stats.shapiro(x), len(x), 's... |
12,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vorhersagen mit trainiertem CNN Modell und Auswertung
Step1: Laden realistischer Daten
Step2: Modell laden
Step3: Bewertung
Step4: Nutzung mit Server Installationen
1. Flask basiert
http... | Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import matplotlib.pylab as plt
import numpy as np
from distutils.version import StrictVersion
import sklearn
print(sklearn.__version__)
assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1')
import tensorflow ... |
12,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom Estimator
Learning Objectives
Step1: Next, we'll load our data set.
Step2: Examine the data
It's a good idea to get to know your data a little bit before you work with it.
We'll pri... | Python Code:
import math
import shutil
import numpy as np
import pandas as pd
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
Explanation: Custom Estimator
Learning Objectives:
* Use a custom estimator of the Estimato... |
12,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Alapozás
Görbék megadási módjai
Implicit alak
Az implicit alak a görbét alkotó pontokat egy teszt formájában adja meg, melynek segítségével el lehet dönteni, hogy egy adott pont rajta fekszi... | Python Code:
addScript("js/c0-parametric-continuity", "c0-parametric-continuity")
Explanation: Alapozás
Görbék megadási módjai
Implicit alak
Az implicit alak a görbét alkotó pontokat egy teszt formájában adja meg, melynek segítségével el lehet dönteni, hogy egy adott pont rajta fekszik-e a görbén. Kétdimenziós esetben ... |
12,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weight By Portfolio Strategy
Basic buy and hold that allows weighting by user specified weights, Equal, Sharpe Ratio, Annual Returns, Std Dev, Vola, or DS Vola.
Rebalance is yearly, monthl... | Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import pinkfish as pf
import strategy
# Format price data.
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
# Set size of inline plots.
'''note: rcParams can't be in same cell as import matplotlib
or %matplotlib inl... |
12,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting and Visualization
There are a handful of third-party Python packages that are suitable for creating scientific plots and visualizations. These include packages like
Step1: The abov... | Python Code:
plt.plot(np.random.normal(size=100), np.random.normal(size=100), 'ro')
Explanation: Plotting and Visualization
There are a handful of third-party Python packages that are suitable for creating scientific plots and visualizations. These include packages like:
matplotlib
Chaco
PyX
Bokeh
Here, we will focus e... |
12,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 1
Imports
Step2: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral
Step3: Now use scipy.integrate.quad to integrate the f an... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
Explanation: Integration Exercise 1
Imports
End of explanation
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
t=(b-a)/N
p=np.linspace(a,b,N+1)
weights=np... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.