Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Переменные" data-toc-modified-id="Переменные-1">Переменные</a></span></li><li><span... | Python Code:
a = 5
b = "Hello, LKSH"
c = 5.0
print(a)
print(b)
print(c)
Explanation: <h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Переменные" data-toc-modified-id="Переменные-1">Переменные</a></span></li><li><span><a href="#Параллельное-присваивание" data-to... |
8,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial, you will learn what a categorical variable is, along with three approaches for handling this type of data.
Introduction
A categorical variable takes only a limited number o... | Python Code:
#$HIDE$
import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
# Separate target from predictors
y = data.Price
X = data.drop(['Price'], axis=1)
# Divide data into training and validation subsets
X_tra... |
8,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: This results in a constant distance of $\delta x$ between all grid points in the $x$ dimension. Using central differences, we can numerically approximate the derivative for ... | Python Code:
nx = 1024
ny = 1024
Explanation: Tutorial: From physics to tuned GPU kernels
This tutorial is designed to show you the whole process starting from modeling a physical process to a Python implementation to creating optimized and auto-tuned GPU application using Kernel Tuner.
In this tutorial, we will use di... |
8,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
8,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuickStart
Step1: For a PoppyErgoJr
Step2: Get robot current status
Step3: Turn on/off the compliancy of a motor
Step4: Go to the zero position
Step5: Make a simple dance movement
On a ... | Python Code:
from poppy.creatures import PoppyErgo
ergo = PoppyErgo()
Explanation: QuickStart: Playing with a Poppy Ergo (or a PoppyErgoJr)
This notebook is still work in progress! Feedbacks are welcomed!
In this tutorial we will show how to get started with your PoppyErgo creature. You can use a PoppyErgoJr instead.
<... |
8,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST using Distributed Keras
Joeri Hermans (Technical Student, IT-DB-SAS, CERN)
Departement of Knowledge Engineering
Maastricht University, The Netherlands
Step1: In this... | Python Code:
!(date +%d\ %B\ %G)
Explanation: MNIST using Distributed Keras
Joeri Hermans (Technical Student, IT-DB-SAS, CERN)
Departement of Knowledge Engineering
Maastricht University, The Netherlands
End of explanation
%matplotlib inline
import numpy as np
import seaborn as sns
from keras.optimizer... |
8,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Goal
We want to build a model $h_\theta(s) \rightarrow a^$ which predicts the mode $a^$ of ... | Python Code:
#@title Default title text
# 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 wri... |
8,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style="width
Step1: We pull out this dataset and call subset() to set up requesting a subset of the data.
Step2: We can then use the ncss object to create a new query object, which
fa... | Python Code:
%matplotlib inline
from siphon.catalog import TDSCatalog
best_gfs = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/'
'Global_0p25deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p25deg/Best')
best_gfs.datasets
Explanation: <div style="width:1000 px">
<div style="float:... |
8,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 사용자 정의 학습
Step2: 붓꽃 분류 문제
당신이 식물학자라고 상상하고, 주어진 붓꽃을 자동적으로 분류하는 방법을 찾고 있다고 가정합시다. 머신러닝은 통계적으로 꽃을 분류할 수 있는 다양한 알고리즘을 제공합니다. 예를 들어, 정교한 머신러닝 프로그램은... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
8,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 3
Step1: Predicting consumption expeditures
The parameters needed to produce the plots are as follows
Step2: Panel B
Step3: Panel C
Step4: Panel D | Python Code:
from fig_utils import *
import matplotlib.pyplot as plt
import time
%matplotlib inline
Explanation: Figure 3: Cluster-level consumptions
This notebook generates individual panels of Figure 3 in "Combining satellite imagery and machine learning to predict poverty".
End of explanation
# Plot parameters
count... |
8,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning with H2O - Tutorial 2
Step1: <br>
Step2: <br>
Explain why we need to transform
<br>
Step3: <br>
Doing the same for 'Pclass'
<br> | Python Code:
# Start and connect to a local H2O cluster
import h2o
h2o.init(nthreads = -1)
Explanation: Machine Learning with H2O - Tutorial 2: Basic Data Manipulation
<hr>
Objective:
This tutorial demonstrates basic data manipulation with H2O.
<hr>
Titanic Dataset:
Source: https://www.kaggle.com/c/titanic/data
<hr>
Fu... |
8,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
観測されたデータ。N(5,1)から作られた10個の乱数。
Step1: [ベイズ推論]</P>
<p>確率変数$X_1, X_2,..., X_n$が互いに独立に平均がμ、分散が1であるような正規分布に従うとする。</p>
<p>μの事前分布にt分布を仮定する。
<P>1 初期値μ^(0)を決め、t=1とおく。</p>
<p>2 現在μ^(t-1)であるとき、次の点μ^tの候... | Python Code:
X = np.zeros(10)
for i in range(len(X)):
X[i] = np.random.normal(5,1)
X
Explanation: 観測されたデータ。N(5,1)から作られた10個の乱数。
End of explanation
class RWMH:
def __init__(self, X):
self.mu = 2
self.freedom = 5.0
self.x_var = np.mean(X)
def prior_dist(self, t):
ft = m... |
8,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
Positional Astronomy
Previous
Step1: Import section specific modules
Step2: 3.4 Direction Cosine Coordinates ($l$,$m$,$n$)
There is another useful astronomical coordinate ... | 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
Positional Astronomy
Previous: 3.3 Horizontal Coordinates (ALT/AZ)
Next: 3.x Further Reading and References
Import standard ... |
8,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Radial Wavefunctions and Quantum Defects
In this tutorial we show how to access quantum defects and wavefunctions, which are used for the computation of matrix elements, using the Python API... | Python Code:
%matplotlib inline
Explanation: Radial Wavefunctions and Quantum Defects
In this tutorial we show how to access quantum defects and wavefunctions, which are used for the computation of matrix elements, using the Python API. Some aspects of this are discussed in Appendix A of the pairinteraction paper J. P... |
8,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGamma15 statistics tutorial
Welcome to the PyGamma15 statistics tutorial!
The actual tutorial will consist of an IPython notebook
with some descriptions and code to get you started,
and in... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import scipy.stats
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.plot([1, 3, 6], [2, 5, 3]);
Explanation: PyGamma15 statistics tutorial
Welcome to the PyGamma15 statistics tutorial!
The actual tutorial will consist of an IPython notebo... |
8,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Web application with Dash
Authors
Step1: Data collection (2/6)
Query d_labitems table (Dictionary table for mapping)
Query labevents table (History of the labitem order)
Join tw... | Python Code:
# # Dash packages installation
# !conda install -c conda-forge dash-renderer -y
# !conda install -c conda-forge dash -y
# !conda install -c conda-forge dash-html-components -y
# !conda install -c conda-forge dash-core-components -y
# !conda install -c conda-forge plotly -y
import dash
import dash_core_comp... |
8,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
Step1: Let us read the ... | Python Code:
import csv
Explanation: Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
End of explanation
with open('cars.csv') as handle:
reader = csv.DictReader(handle, delimiter=',')
Data = [... |
8,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Responses for RXTE HEXTE
Step1: Sherpa Stuff
Daniela is doing some sherpa testing right now ...
Step2: RXTE does not have BIN_LO and BIN_HI set. Because of course it doesn't.
Step3: RXTE ... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
# try:
# import seaborn as sns
# except ImportError:
# print("No seaborn installed. Oh well.")
import numpy as np
# import pandas as pd
import astropy.io.fits as fits
from astropy.table import Table
import sherpa.astro.ui as ui
import astropy... |
8,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fuzzy Logic for Python 3
The doctests in the modules should give a good idea how to use things by themselves, while here are some examples how to use everything together.
Installation
First ... | Python Code:
from matplotlib import pyplot
pyplot.rc("figure", figsize=(10, 10))
from fuzzylogic.classes import Domain
from fuzzylogic.functions import R, S, alpha
T = Domain("test", 0, 30, res=0.1)
T.up = R(1,10)
T.up.plot()
T.down = S(20, 29)
T.down.plot()
T.polygon = T.up & T.down
T.polygon.plot()
T.inv_polygon = ~T... |
8,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t... | Python Code:
# As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver
%matplot... |
8,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
discretize a point in a (3,3) matrix
Step1: randomwalk each point for 1 day equivalent
Step2: make a grid from a scatter of many points
Step3: Find maximum time step without leaking mosqu... | Python Code:
def findquadrant(point,size):
y,x = point
halfsize = size/2
if x < -halfsize:
if y > halfsize: return [0,0]
if y < -halfsize: return [2,0]
return [1,0]
if x > halfsize:
if y > halfsize: return [0,2]
if y < -halfsize: return [2,2]
return [1,2]
... |
8,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stage 5, Report
https
Step1: Filling in Missing Values
Step2: Generating Features
Here, we generate all the features we decided upon after our final iteration of cross validation and debug... | Python Code:
import py_entitymatching as em
import os
import pandas as pd
# specify filepaths for tables A and B.
path_A = 'tableA.csv'
path_B = 'tableB.csv'
# read table A; table A has 'ID' as the key attribute
A = em.read_csv_metadata(path_A, key='id')
# read table B; table B has 'ID' as the key attribute
B = em.rea... |
8,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Frequency-tagging
Step1: Data preprocessing
Due to a generally high SNR in SSVEP/vSSR, typical preprocessing steps
are considered optional. This doesn't mean, that a proper cleaning would n... | Python Code:
# Authors: Dominik Welke <dominik.welke@web.de>
# Evgenii Kalenkovich <e.kalenkovich@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
import numpy as np
from scipy.stats import ttest_rel
Explanation: Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
In this ... |
8,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ATM 623
Step1: Contents
Simulation versus parameterization of heat transport
The temperature diffusion parameterization
Solving the temperature diffusion equation with climlab
Parameterizin... | Python Code:
# Ensure compatibility with Python 2 and 3
from __future__ import print_function, division
Explanation: ATM 623: Climate Modeling
Brian E. J. Rose, University at Albany
Lecture 18: The one-dimensional energy balance model
Warning: content out of date and not maintained
You really should be looking at The ... |
8,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You are currently looking at version 1.2 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ... | Python Code:
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.ren... |
8,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tick-locators
Step1: Note that the Y axis in this plot has sensible ticks that cover the full data domain $[0, 1]$, while the X axis also has sensible ticks that include "round" numbers... | Python Code:
import numpy
x = numpy.arange(20)
y = numpy.linspace(0, 1, len(x)) ** 2
import toyplot
canvas, axes, mark = toyplot.plot(x, y, width=300)
Explanation: .. _tick-locators:
Tick Locators
When you create a figure in Toyplot, you begin by creating a :class:canvas<toyplot.canvas.Canvas>, add :mod:axes<t... |
8,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The JAX emulator
Step1: Generate CIGALE SEDs
Step2: Generate values for CIGALE
Redshift
Step3: AGN frac
Step4: DeepNet building
I will build a multi input, multi output deepnet model as ... | Python Code:
from astropy.cosmology import WMAP9 as cosmo
import jax
import numpy as onp
import pylab as plt
import astropy.units as u
import scipy.integrate as integrate
%matplotlib inline
import jax.numpy as np
from jax import grad, jit, vmap, value_and_grad
from jax import random
from jax import vmap # for auto-vect... |
8,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 5
The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data.
Step2: Download the data from the source website if necessary.
Step4: Read th... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab... |
8,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculating radial distribution functions
Radial distribution functions can be calculated from one or more pymatgen Structure objects by using the vasppy.rdf.RadialDistributionFunction class... | Python Code:
# Create a pymatgen Structure for NaCl
from pymatgen import Structure, Lattice
# Create a pymatgen Structure for NaCl
from pymatgen import Structure, Lattice
a = 5.6402 # NaCl lattice parameter
lattice = Lattice.from_parameters(a, a, a, 90.0, 90.0, 90.0)
lattice
structure = Structure.from_spacegroup(sg='Fm... |
8,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Memory consumption
Step1: Counting error rate | Python Code:
import collections
import subprocess
import itertools
import os
import time
import madoka
import numpy as np
import redis
ALPHANUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
NUM_ALPHANUM_COMBINATION = 238328
zipf_array = np.random.zipf(1.5, NUM_ALPHANUM_COMBINATION)
def python_memor... |
8,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PLEASE MAKE A COPY BEFORE CHANGING
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
... | Python Code:
!pip install -q lifetimes
!pip install -q --upgrade git+https://github.com/HIPS/autograd.git@master
!pip install -U -q PyDrive
from google.colab import auth
from googleapiclient.discovery import build
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.client import... |
8,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instanciation de poppyrate
Exemple d'instanciation d'un poppyrate tel qu'il pourrais être lancé comme service, avec un serveur snap, http et remote(rpc).
Ce notebook peut servir de base à du... | Python Code:
import logging
import logging.handlers
from poppy_rate import PoppyRate
import poppy_rate
import poppy_rate.primitives as pp
Explanation: Instanciation de poppyrate
Exemple d'instanciation d'un poppyrate tel qu'il pourrais être lancé comme service, avec un serveur snap, http et remote(rpc).
Ce notebook peu... |
8,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
News Headline Analysis
In this project we're analyzing news headlines written by two journalists – a finance reporter from the Business Insider, and a celebrity reporter from the Huffington ... | Python Code:
from pattern.en import parsetree
Explanation: News Headline Analysis
In this project we're analyzing news headlines written by two journalists – a finance reporter from the Business Insider, and a celebrity reporter from the Huffington post – to find similarities and differences between the ways that these... |
8,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hardware simulators - gem5 target support
The gem5 simulator is a modular platform for computer-system architecture research, encompassing system-level architecture as well as processor micr... | Python Code:
from conf import LisaLogging
LisaLogging.setup()
# One initial cell for imports
import json
import logging
import os
from env import TestEnv
# Suport for FTrace events parsing and visualization
import trappy
from trappy.ftrace import FTrace
from trace import Trace
# Support for plotting
# Generate plots in... |
8,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$ \LaTeX \text{ command declarations here.}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\D}{\mathcal{D}}
\newcommand{\G}{\mathca... | Python Code:
import numpy as np
np.set_printoptions(suppress=True)
parts_of_speech = DETERMINER, NOUN, VERB, END = 0, 1, 2, 3
words = THE, DOG, CAT, WALKED, RAN, IN, PARK, END = 0, 1, 2, 3, 4, 5, 6, 7
# transition probabilities
A = np.array([
# D N V E
[0.1, 0.8, 0.1, 0.0], # D: determiner most... |
8,535 | 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', 'ec-earth-consortium', 'ec-earth3-gris', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-GRIS
Topic: Land
S... |
8,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Given a list of values, there are several ways to count the frequency of each value.
Step2: You can use a Python dictionary... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import nsfg
import first
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
End of explanation
t = [1, ... |
8,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpretive Tag Statistics for Katherine Mansfield's "The Garden Party"
First, let's get all the necessary programming libraries that will allow us to do these computations.
Step1: Next, l... | Python Code:
from bs4 import BeautifulSoup # For processing XMLfrom BeautifulSoup
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import itertools
from math import floor
matplotlib.style.use('ggplot')
import numpy as np
Explanation: Interpretive Tag Statistics for Katherine Man... |
8,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting with matplotlib
The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figu... | Python Code:
%matplotlib inline
import numpy
import matplotlib.pyplot as plt
Explanation: Plotting with matplotlib
The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figures. If you are interested in learning ... |
8,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Iterable Operation Extensions
<--- Back
Table of Contents for this notebook
The Iterable Operation Extensions
Table of Contents for this notebook
Overview
IterEnumerateInstances
IterEnum... | Python Code:
import pywbem
# Global variables used by all examples:
server = 'http://localhost'
username = 'user'
password = 'password'
namespace = 'root/cimv2'
classname = 'CIM_ComputerSystem'
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=na... |
8,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python and Natural Language Technologies
Type system and built-in types
Lecture 02
13 September 2017
PEP8, the Python style guide
widely accepted style guide for Python
PEP8 ... | Python Code:
i = 2
type(i), id(i)
i = "foo"
type(i), id(i)
Explanation: Introduction to Python and Natural Language Technologies
Type system and built-in types
Lecture 02
13 September 2017
PEP8, the Python style guide
widely accepted style guide for Python
PEP8 by Guido himself, 2001
Specifies:
indentation
line length
... |
8,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, make the validation set with different drivers
Step1: fastai's statefarm has 3478 pics in validation set and 18946 in training, so let's get something close to that
Step2: now start... | Python Code:
%%bash
cut -f 1 -d ',' driver_imgs_list.csv | grep -v subject | uniq -c
lines=$(expr `wc -l driver_imgs_list.csv | cut -f 1 -d ' '` - 1)
echo "Got ${lines} pics"
Explanation: First, make the validation set with different drivers
End of explanation
import csv
import os
to_get = set(['p081','p075', 'p072', '... |
8,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The resilu linearity / non-linearity
The function $resilu(x)=\frac{x}{1-e^{-x}}$ can be written as the sum of a linear funciton and a function that limits to relu(x).
By using resilu(x) and ... | Python Code:
import copy
import numpy as np
import matplotlib.pyplot as plt
import math
import sympy
x=np.arange(-20,20,0.01)
def resilu(x):
return x/(1.0-np.exp(x*-1.0))
def relu(x):
y=copy.copy(x)
y[y<0]=0.0
return y
Explanation: The resilu linearity / non-linearity
The function $resilu(x)=\frac{... |
8,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Questão 1
Step1: Questão 2
Step2: Questão 3
Step3: Questão 4 | Python Code:
import numpy as np
from math import pi
import matplotlib.pyplot as plot
%matplotlib notebook
x = np.arange(-5, 5.001, 0.0001)
y = (x**4)-(16*(x**2)) + 16
plot.plot(x,y,'c')
plot.grid(True)
Explanation: Questão 1: Faça um gráfico da função $f(x) = x^4-16x^2+16$ para x de -5 a 5.
Coloque a grade.
Olhando pa... |
8,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image features exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more detai... | Python Code:
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading ex... |
8,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Challenge Problems
1. Spinodal Decomposition - Cahn-Hilliard
1.1 Parameter Values
1.2 Initial Conditions
1.3 Domains
1.a Square Periodic
1.b No Flux
1.c T-Shape No Flux
1.d... | Python Code:
from IPython.display import SVG
SVG(filename='../images/block1.svg')
Explanation: Table of Contents
Challenge Problems
1. Spinodal Decomposition - Cahn-Hilliard
1.1 Parameter Values
1.2 Initial Conditions
1.3 Domains
1.a Square Periodic
1.b No Flux
1.c T-Shape No Flux
1.d Sphere
1.4 Tasks
2. Ostwald Ripeni... |
8,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The purpose of this product is to classify population depending on their uses of their phone and phone brands. This classification is the first step to tailor advertising campai... | Python Code:
#Uplaod the data into the notbook and select the rows that will be used after previous visual inspection of the datasets
datadir = 'D:/Users/Borja.gonzalez/Desktop/Thinkful-DataScience-Borja'
gatrain = pd.read_csv('gender_age_train.csv',usecols=['device_id','gender','age','group'] )
gatest = pd.read_csv('g... |
8,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea... |
8,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kernel hypothesis testing in Shogun
By Heiko Strathmann - <a href="mailto
Step1: Some Formal Basics (skip if you just want code examples)
To set the context, we here briefly describe statis... | Python Code:
%pylab inline
%matplotlib inline
# import all Shogun classes
from modshogun import *
Explanation: Kernel hypothesis testing in Shogun
By Heiko Strathmann - <a href="mailto:heiko.strathmann@gmail.com">heiko.strathmann@gmail.com</a> - <a href="github.com/karlnapf">github.com/karlnapf</a> - <a href="herrstrat... |
8,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dataset
Step1: RF
Step2: GBT
$$\tilde{x}^m = \tilde{x}^{m-1} - \lambda_m \nabla f(\tilde{x}^{m-1})$$
$$\tilde{y}^m = \tilde{y}^{m-1} - \lambda_m \nabla Q(\tilde{y}^{m-1}, y)$$
$$b_i = lear... | Python Code:
def ground_truth(x):
return x * np.sin(x) + np.sin(2 * x)
def gen_data(n_samples=200):
np.random.seed(13)
x = np.random.uniform(0, 10, size=n_samples)
x.sort()
y = ground_truth(x) + 0.75 * np.random.normal(size=n_samples)
train_mask = np.random.randint(0, 2, size=n_samples).astype(n... |
8,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Bonus Materials I | Contents >
Bonus Materials II
Vectorised backtesting
Step1: Experiment With the Training Data Set
Step2: Vectorized Backtesting With the Test Set - ... | Python Code:
import numpy as np
import pandas as pd
import oandapy
import configparser
%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
config = configparser.ConfigParser()
config.read('../config/config_v1.ini')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']
oand... |
8,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Préstamos
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... | Python Code:
# Importa la librería financiera.
# Solo es necesario ejecutar la importación una sola vez.
import cashflows as cf
Explanation: Préstamos
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 ú... |
8,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Rates Information | Contents | Order Management >
Account Information
OANDA REST-V20 API Wrapper Doc on Account
OANDA API Getting Started
OANDA API Account
Account Detail... | Python Code:
import pandas as pd
import oandapyV20
import oandapyV20.endpoints.accounts as accounts
import configparser
config = configparser.ConfigParser()
config.read('../config/config_v20.ini')
accountID = config['oanda']['account_id']
access_token = config['oanda']['api_key']
client = oandapyV20.API(access_token=ac... |
8,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CD of Vinyl?
Gisteren deed mijn collega de boude uitspraak dat er steeds meer en meer op vinyl uitgebracht werd. Ik vroeg me af hoe sterk die gevoelde stijging was en besloot om snel een gra... | Python Code:
from pandas import read_csv
df = read_csv("carriers.csv", delimiter=",", quoting=1, escapechar="\\", header=None)
df.columns = ["Titel", "Jaar van uitgave", "Type drager"]
df.head()
Explanation: CD of Vinyl?
Gisteren deed mijn collega de boude uitspraak dat er steeds meer en meer op vinyl uitgebracht werd.... |
8,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 2 - Drawing the Network
Drawing the Data
Now that we have a file containing the data that represents our network, we just need to load it and graph it. First, run the cell below by clic... | Python Code:
import wikinetworking as wn
import networkx as nx
import matplotlib.pyplot as plt
from pyquery import PyQuery
%matplotlib inline
print "OK"
Explanation: Part 2 - Drawing the Network
Drawing the Data
Now that we have a file containing the data that represents our network, we just need to load it and graph i... |
8,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
ZoneBudget Example
This notebook demonstrates how to use the ZoneBudget class to extract budget information from the cell by cell budget file using an array of zones.
First set the pat... | Python Code:
%matplotlib inline
from __future__ import print_function
import os
import sys
import platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__version__))
print('matplotlib version: {}'.form... |
8,556 | Given the following text description, write Python code to implement the functionality described.
Description:
Range and Update Sum Queries with Factorial
Python3 program to calculate sum of factorials in an interval and update with two types of operations ; Modulus ; Maximum size of input array ; Size for factorial ar... | Python Code:
from bisect import bisect_left as lower_bound
MOD = 1e9
MAX = 100
SZ = 40
BIT =[0 ] *(MAX + 1 )
fact =[0 ] *(SZ + 1 )
class queries :
def __init__(self , tpe , l , r ) :
self . type = tpe
self . l = l
self . r = r
def update(x , val , n ) :
global BIT
while x <= n :
BIT[... |
8,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Consider sequences that are increasingly different. EDeN allows to turn them into vectors, whose similarity is decreasing.
Step1: Build an artificial dataset
Step2: define a functi... | Python Code:
%matplotlib inline
Explanation: Example
Consider sequences that are increasingly different. EDeN allows to turn them into vectors, whose similarity is decreasing.
End of explanation
import random
def make_data(size):
text = ''.join([str(unichr(97+i)) for i in range(26)])
seqs = []
def swap_two_... |
8,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
verify pyEMU null space projection with the freyberg problem
Step1: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the p... | Python Code:
%matplotlib inline
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pyemu
Explanation: verify pyEMU null space projection with the freyberg problem
End of explanation
mc = pyemu.MonteCarlo(jco="freyberg.jcb",verbose=False,forecasts=[])
mc.drop_prior_info... |
8,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting curve to data
Within this notebook we do some data analytics on historical data to feed some real numbers into the model. Since we assume the consumer data to be resemble a sinus, du... | Python Code:
import pandas as pd
import numpy as np
from scipy.optimize import leastsq
import pylab as plt
N = 1000 # number of data points
t = np.linspace(0, 4*np.pi, N)
data = 3.0*np.sin(t+0.001) + 0.5 + np.random.randn(N) # create artificial data with noise
guess_mean = np.mean(data)
guess_std = 3*np.std(data)/(2**0... |
8,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic data IO and analysis
First, we need to import all the necessary libraries and set up some environment variables.
Step1: Load the zip file from the web and save it to your hard drive.
... | Python Code:
import re
import requests
import zipfile
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns
import statsmodels.formula.api as sm
sns.set_context('talk')
pd.set_option('float_format', '{:6.2f}'.format)
%matplotlib inline
Explanation: Basic data IO and analysis
First,... |
8,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Projection, Joining, and Sorting
Setup
Step1: Projections
Step2: First, the basics
Step3: You can make a list of columns you want, too, and pass that
Step4: You can also use the explicit... | Python Code:
import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',
hdfs_client=hdfs)
print('Hello!')
Explanation: Projectio... |
8,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
人生苦短,我用python
泰坦尼克数据处理与分析
<img src='https
Step1: 导入数据
Step2: 快速预览
Step3: | 单词 | 翻译
| ---
Step4: 处理空值
Step5: 尝试从性别进行分析
Step6: 通过上面图片可以看出:性别特征对是否生还的影响还是挺大的
从年龄进行分析
Step7: 分析票价
Step8: ... | Python Code:
import pandas as pd
%matplotlib inline
Explanation: 人生苦短,我用python
泰坦尼克数据处理与分析
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502440065892&di=51db15bf76374068735a690806ad66a2&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201607%2F20160708007.jpg'>
End of explanation
# 如果不... |
8,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 비정형 텐서
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: 개요
데이터는 다양한 형태로 제공됩니다; 텐서도 마찬가지입니다.
... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
8,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Catalyst Cooperative Jupyter Notebook Template
This notebook lays out a standard format and some best practices for creating interactive / exploratory notebooks which can be relatively easil... | Python Code:
%load_ext autoreload
%autoreload 2
# Standard libraries
import logging
import os
import pathlib
import sys
# 3rd party libraries
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
import seaborn as sns
import sqlalchemy as sa
# Local libraries
import pudl
Explan... |
8,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicios 4
1 Ejercicio
Escribir una función que indique si dos fichas de dominó encajan o no. Las fichas son recibidas en dos tuplas, por ejemplo
Step1: 2 Ejercicio
Define la función med... | Python Code:
# Sol:
x = (3,2)
y = (5,3)
def encaja(x, y):
if x[0] == y[0]:
print("Encajan en la posición X[0] Y[0]")
elif x[0] == y[1]:
print("Encajan en la posición X[0] Y[1]")
elif x[1] == y[0]:
print("Encajan en la posición X[1] Y[0]")
elif x[1] == y[1]:
print("Encajan... |
8,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissions, ... |
8,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First iteration of modeling, going through several different classification algorithms. Of these, Gradient Boosted Classifier using unscaled data worked the best.
For reference/example only.... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cPickle as pickle
%matplotlib notebook
plt.style.use('ggplot')
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split, KFold
from sklearn.metrics import confusion_matrix, roc_auc_sc... |
8,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
网络科学理论简介
天涯论坛的回帖网络分析
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Extract @
Step2: @贾也2012-10-297 | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
dtt = []
file_path = '../data/tianya_bbs_threads_network.txt'
with open(file_path, 'r') as f:
for line in f:
pnum, link, time, author_id, author,\
content = line.replace('\n', '').split('\t')
dtt.append([pnum, link, time, author... |
8,569 | 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... |
8,570 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
So I fed the testing data, but when I try to test it with clf.predict() it just gives me an error. So I want it to predict on the data that i give, which is the last close price, th... | Problem:
from sklearn import tree
import pandas as pd
import pandas_datareader as web
import numpy as np
df = web.DataReader('goog', 'yahoo', start='2012-5-1', end='2016-5-20')
df['B/S'] = (df['Close'].diff() < 0).astype(int)
closing = (df.loc['2013-02-15':'2016-05-21'])
ma_50 = (df.loc['2013-02-15':'2016-05-21'])
ma_1... |
8,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore microfluidic flow rate and pressure according to a defined geometry
Date
Step1: Define some initial conditions (feel free to test others conditions)
Step2: Calculate pressure nee... | Python Code:
%matplotlib qt
import numpy as np
import matplotlib.pyplot as plt
def calculcate_section_circle(diameter):
return np.pi * ((diameter / 2) ** 2)
def calculcate_section_rectangle(height, width):
return height * width
def calculate_characteristic_length_circle(diameter):
return diameter
def calcul... |
8,572 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Lasso - Training a Lasso Regression Model
| Python Code::
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error
# initialise & fit Lasso regression model with alpha set to 0.5
model = Lasso(alpha=0.5)
model.fit(X_train, y_train)
# create dict... |
8,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Making and manipulating structures with ASE
For preparing and manipulating crystal structures we will be using the ASE Python library. The documentation is rather accessible and even include... | Python Code:
from ase.spacegroup import crystal
a = 4.5
Na_unitcell = crystal('Na', [(0,0,0)], spacegroup=229, cellpar=[a, a, a, 90, 90, 90])
print('hello')
Explanation: Making and manipulating structures with ASE
For preparing and manipulating crystal structures we will be using the ASE Python library. The documentati... |
8,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Numerical Problem Solving TX00BY09-3007
Assignment
Step1: Exercise 04
Given equation system
$$10.0x_1 + 2.0x_2 − x_3 = 27.0$$
$$−3.0x_1 − 6.0x_2 + 2.0x_3 = −61.5$$
$$x_1 + x... | Python Code:
# Import required libraries
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import *
from numpy import *
Explanation: Introduction to Numerical Problem Solving TX00BY09-3007
Assignment: 04 Graphical analysis<br />
Description: From the exercises 04, solve the... |
8,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
가우시안 정규 분포
가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다.
정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수... | Python Code:
mu = 0
std = 1
rv = sp.stats.norm(mu, std)
rv
Explanation: 가우시안 정규 분포
가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다.
정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수(pdf: probability density function)는 다음과 같은 수식을 가진다.
$$ \m... |
8,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
sklearn构建管道
sklearn支持使用管道(Pipeline)连接多个sklearn中的模型类实例,但要求过程中的模型类对象带transform方法的且最后一个需要是分类器,回归器或者同样是带transform方法的模型类对象.
带transform方法的类对象叫做转换器,可以使用sklearn.preprocessing.FunctionTransformer自定义.... | Python Code:
import numpy as np
from sklearn.preprocessing import FunctionTransformer
transformer = FunctionTransformer(np.log1p)
X = np.array([[0, 1], [2, 3]])
transformer.transform(X)
Explanation: sklearn构建管道
sklearn支持使用管道(Pipeline)连接多个sklearn中的模型类实例,但要求过程中的模型类对象带transform方法的且最后一个需要是分类器,回归器或者同样是带transform方法的模型类对象.
带t... |
8,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Metric Learning with the Shogun Machine Learning Toolbox
Building up the intuition to understand LMNN
First of all, let us introduce LMNN through a simple example. For this purpose, we will ... | Python Code:
%pylab inline
x = numpy.array([[0,0],[-1,0.1],[0.3,-0.05],[0.7,0.3],[-0.2,-0.6],[-0.15,-0.63],[-0.25,0.55],[-0.28,0.67]])
y = numpy.array([0,0,0,0,1,1,2,2])
Explanation: Metric Learning with the Shogun Machine Learning Toolbox
Building up the intuition to understand LMNN
First of all, let us introduce LMNN... |
8,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
解释器模式(Interpret Pattern)
1 代码
要开发一个自动识别谱子的吉他模拟器,达到录入谱即可按照谱发声的效果。除了发声设备外(假设已完成),最重要的就是读谱和译谱能力了。分析其需求,整个过程大致上分可以分为两部分:根据规则翻译谱的内容;根据翻译的内容演奏。我们用一个解释器模型来完成这个功能。
Step1: PlayContext类为谱的内容,这里仅含一个字段... | Python Code:
class PlayContext():
play_text = None
class Expression():
def interpret(self, context):
if len(context.play_text) == 0:
return
else:
play_segs=context.play_text.split(" ")
for play_seg in play_segs:
pos=0
for ele in... |
8,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling TRISO Particles
OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capability is not a stochasti... | Python Code:
%matplotlib inline
from math import pi
import numpy as np
import matplotlib.pyplot as plt
import openmc
import openmc.model
Explanation: Modeling TRISO Particles
OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capabilit... |
8,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring hddm
Step1: Quick-Start Tutorial
As found in the hddm repo README file - see https
Step2: Notes on MCMC sampling
Step3: print_stats() is literally just a printer - it doesn't re... | Python Code:
%matplotlib inline
Explanation: Exploring hddm
End of explanation
import hddm
# Load csv data - converted to numpy array
data = hddm.load_csv('../examples/hddm_simple.csv')
# Create hddm model object
model = hddm.HDDM(data, depends_on={'v': 'difficulty'})
# Markov chain Monte Carlo sampling
model.sample(20... |
8,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class Coding Lab
Step1: If you look through the output, you'll see a factorial name. Let's see if it's a function we can use
Step2: It says it's a built-in function, and requies an integer... | Python Code:
import math
dir(math)
Explanation: Class Coding Lab: Functions
The goals of this lab are to help you to understand:
How to use Python's built-in functions in the standard library.
How to write user-defined functions
How to use other people's code.
The benefits of user-defined functions to code reuse and si... |
8,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TimML Notebook 3
Inhomogeneities
Consider a two-aquifer system that contains one inhomogeneity. Inside the inhomogeneity the transmissivity
of the top aquifer is much lower and the transmiss... | Python Code:
%matplotlib inline
from timml import *
from pylab import *
figsize = (8, 8)
ml = ModelMaq(kaq=[10, 20], z=[20, 0, -10, -30], c=[4000])
xy1 = [(0, 600), (-100, 400), (-100, 200), (100, 100), (300, 100), (500, 100),
(700, 300), (700, 500), (600, 700), (400, 700), (200, 600)]
p1 = PolygonInhomMaq(ml, x... |
8,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Datenanalyse-4
Step1: A tutorial on statistical-learning for scientific data processing
Step2: Nearest Neighbour
Step3: Model sel... | Python Code:
from sklearn import datasets
iris = datasets.load_iris()
digits = datasets.load_digits()
iris.data[10]
iris.target
print(digits.data)
digits.target
digits.images[0]
from sklearn import svm
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(digits.data[:-1], digits.target[:-1])
clf.predict(digits.data[-1])
from s... |
8,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Spark SQL via PySpark
Goals
Step1: What is a SparkSession?
It is the driver process that controls a spark application
A SparkSession instance is responsible for executing th... | Python Code:
from pyspark.sql import SparkSession
Explanation: Introduction to Spark SQL via PySpark
Goals:
Get familiarized with the basics of Spark SQL and PySpark
Learn to create a SparkSession
Verify if Jupyter can talk to Spark Master
References:
* https://spark.apache.org/docs/latest/api/python/pyspark.html
* htt... |
8,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RPartVariables
This script runs repeated cross-validation as a search for suitable parameter values for RPart.
It has been re-run for all data-sets and the plotted results for each were cons... | Python Code:
# import stuffs
%matplotlib inline
import numpy as np
import pandas as pd
from pyplotthemes import get_savefig, classictheme as plt
from lifelines.utils import k_fold_cross_validation
plt.latex = True
Explanation: RPartVariables
This script runs repeated cross-validation as a search for suitable parameter ... |
8,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
Step1: Basic Heat map
Step2: Heat map with axes
Step3: Non Uniform Heat map
Step4: Alignment of the data with respect to the grid
For a N-by-N matrix, N+1 points along the row o... | Python Code:
np.random.seed(0)
data = np.random.randn(10, 10)
Explanation: Get Data
End of explanation
col_sc = ColorScale()
grid_map = GridHeatMap(color=data, scales={'color': col_sc})
Figure(marks=[grid_map], padding_y=0.0)
grid_map.display_format = '.2f'
grid_map.font_style={'font-size': '12px', 'fill':'black', 'fon... |
8,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Causal Effect
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Utility function
We define a utility function to draw the dire... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: Causal Effect
Import and settings
In this example, we need to import numpy, p... |
8,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Car Evaluation Database
Car Evaluation Database was derived from a simple hierarchical decision model originally developed for the demonstration of DEX (M. Bohanec, V. Rajkovic
Step1: Dipla... | Python Code:
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(color_codes=True)
# Reading Dataset
df = pd.read_csv("car.data",sep=',',header=None, names=['buying','maintenance','doors','persons','luggage','safety','carClass... |
8,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 class="alert alert-info">Download Data <small> <i class="icon-download"></i> Get All Available MAF Files from TCGA Data Portal</small></h1>
Step1: <div class='alert alert-warning' sty... | Python Code:
import NotebookImport
from Imports import *
from bs4 import BeautifulSoup
from urllib2 import HTTPError
Explanation: <h1 class="alert alert-info">Download Data <small> <i class="icon-download"></i> Get All Available MAF Files from TCGA Data Portal</small></h1>
End of explanation
PATH_TO_CACERT = '/cellar... |
8,590 | 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 ... |
8,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: 第2章 関数近似(補間)
教科書第2章に載っているアルゴリズムを実装していきます。
各種ライブラリのインポート・後で使う汎用関数を定義
Step4: 式(2.5)の実装
n+1個の点列を入力し、逆行列を解いて、補間多項式を求め、n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す
INPUT
points
Step5: 式(2.7)の実装
補... | Python Code:
#!/usr/bin/python
#-*- encoding: utf-8 -*-
Copyright (c) 2015 @myuuuuun
https://github.com/myuuuuun/NumericalCalculation
This software is released under the MIT License.
%matplotlib inline
from __future__ import division, print_function
import math
import numpy as np
import functools
import sys
import type... |
8,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Uncertainty analysis of a 2-D slice model
Possible paper titles
Step1: Model set-up
Subsequently, we will use a model from the "Atlas of Structural Geophysics" as an example model.
Step2: ... | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# here the usual imports. If any of the imports fails,
# make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop'
# or 'python setup.py install'
import sys, os
... |
8,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Booleans
Step1: Python truth value testing
Any object can be tested for truth value
Truth value testing is used in flow control or in Boolean operations
All objects are evaluated as True ex... | Python Code:
# Let's declare some bools
spam = True
print spam
print type(spam)
eggs = False
print eggs
print type(eggs)
Explanation: Booleans
End of explanation
# Let's try boolean operations
print True or True
print True or False
print False or True # Boolean or. Short-circuited, so it only evaluates the second arg... |
8,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving a Laplace problem with Dirichlet boundary conditions
Background
Laplace problem inside the unit sphere with Dirichlet boundary conditions. Let $\Omega$ be the unit sphere with bounda... | Python Code:
import bempp.api
import numpy as np
Explanation: Solving a Laplace problem with Dirichlet boundary conditions
Background
Laplace problem inside the unit sphere with Dirichlet boundary conditions. Let $\Omega$ be the unit sphere with boundary $\Gamma$. Let $\nu$ be the outward pointing normal on $\Gamma$. T... |
8,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 3
Step1: And the script to compute those files can be found here
Step2: Now let's start with the ANTs normalization workflow!
Imports
First, we need to import all modules we later ... | Python Code:
!tree /data/antsdir/sub-0*/
Explanation: Example 3: Normalize data to MNI template
This example covers the normalization of data. Some people prefer to normalize the data during the preprocessing, just before smoothing. I prefer to do the 1st-level analysis completely in subject space and only normalize th... |
8,596 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) | Problem:
import numpy as np
a = np.arange(12).reshape(3, 4)
del_col = np.array([1, 2, 4, 5])
mask = (del_col <= a.shape[1])
del_col = del_col[mask] - 1
result = np.delete(a, del_col, axis=1) |
8,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's see if we can get Aaron's delay network to recognize two different patterns that are multidimensional. We want patterns where you need information from both dimensions, so let's do ph... | Python Code:
s_pattern = 4000 # number of data points in the pattern
t = np.arange(s_pattern)*0.001 # time points for the elements in the pattern
D = 2
pattern1 = np.vstack([np.sin(t*np.pi), np.cos(t*np.pi)]).T
pattern2 = np.vstack([np.sin(t*np.pi), -np.sin(t*np.pi)]).T
plt.subplot(1, 2, 1)
plt.plot(t, ... |
8,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PMOD Grove PIR Motion Sensor
This example shows how to use the Grove PIR motion sensor.
This demo requires the Grove PIR motion sensor and PYNQ Grove Adapter.
1. Download overlay
Download th... | Python Code:
from time import sleep
from pynq import Overlay
from pynq.board import LED
from pynq.iop import Grove_PIR
from pynq.iop import PMODA
from pynq.iop import PMOD_GROVE_G1
ol1 = Overlay("base.bit")
ol1.download()
pir = Grove_PIR(PMODA,PMOD_GROVE_G1)
Explanation: PMOD Grove PIR Motion Sensor
This example shows ... |
8,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 3 lecture notes
Exercise 2 review - common mistakes
Including directories in paths
If you create a file in a lower directory, then want to modify, move, or delete it, you have to use th... | Python Code:
!mkdir mydirectory
!ls > mydirectory/myfiles.txt
!rm myfiles.txt
!rm mydirectory/myfiles.txt
!ls mydirectory
Explanation: Week 3 lecture notes
Exercise 2 review - common mistakes
Including directories in paths
If you create a file in a lower directory, then want to modify, move, or delete it, you have to u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.