Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
13,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
练习 1:仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki$的完整代码,写程序,可求m!+n!+k!
Step1: 练习 2:写函数可返回1 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。
Step2: 练习 3:将task3中的练习1及练习4改写为... | Python Code:
def total (m):
i=0
result=1
while i<m:
i+=1
result*=i
return result
m=int(input('please enter an integer. '))
n=int(input('please enter an integer. '))
k=int(input('please enter an integer. '))
print('The result of ',m,'!+',n,'!+',k,'! is :',total(m)+total(n)+total(k))
Expla... |
13,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
tICA vs. PCA
This example uses OpenMM to generate example data to compare two methods for dimensionality reduction
Step1: Run Dynamics
Okay, let's run the dynamics. The first plot below sho... | Python Code:
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
xx, yy = np.meshgrid(np.linspace(-2,2), np.linspace(-3,3))
zz = 0 # We can only visualize so many dimensions
ww = 5 * (xx-1)**2 * (xx+1)**2 + yy**2 + zz**2
c = plt.contourf(xx, yy, ww, np.linspace(-1, 15, 20), cmap='viridis_r')
plt.... |
13,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linux Interactive System Analysis DEMO
Get LISA and start the Notebook Server
Official repository on GitHub - ARM Software
Step1: <br><br><br><br>
Advanced usage
Step2: Commands execution ... | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
# Execute this cell to enable verbose SSH commands
logging.getLogger('ssh').setLevel(logging.DEBUG)
# Other python modules required by this notebook
import json
import os
Explanation: Linux Interactive System Analysis DEMO
Get LISA and start t... |
13,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APS terrain analysis
Imports
Step1: |Id |Name|
|---|---|
|3003 |Nordenskiöld Land|
|3007 |Vest-Finnmark|
|3009 |Nord-Troms|
|3010 |Lyngen|
|3011 |Tromsø|
|3012 |Sør-Troms|
|... | Python Code:
# -*- coding: utf-8 -*-
%matplotlib inline
from __future__ import print_function
import pylab as plt
import datetime
import netCDF4
import numpy as np
import numpy.ma as ma
from linecache import getline
plt.rcParams['figure.figsize'] = (14, 6)
Explanation: APS terrain analysis
Imports
End of explanation
##... |
13,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Geekbench benchmark on Android
Geekbench4 is an app offering several benchmarks to run on android smartphones. The one used in this notebook is the 'CPU' benchmark, which runs several worklo... | Python Code:
from conf import LisaLogging
LisaLogging.setup()
%pylab inline
import json
import os
# Support to access the remote target
import devlib
from env import TestEnv
# Import support for Android devices
from android import Screen, Workload
# Support for trace events analysis
from trace import Trace
# Suport for... |
13,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading network data
CSV -> List of Dictionaries -> igraph
sand's underlying graph implementation is igraph. igraph offers several ways to load data, but sand provides a few convenience func... | Python Code:
import sand
Explanation: Loading network data
CSV -> List of Dictionaries -> igraph
sand's underlying graph implementation is igraph. igraph offers several ways to load data, but sand provides a few convenience functions that simplify the workflow:
End of explanation
edgelist_file = './data/lein-topology-5... |
13,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ApJdataFrames 008
Step1: Table 1 - VOTable with all source properties
Step3: Cross match with SIMBAD
Step4: Save the data table locally. | Python Code:
import warnings
warnings.filterwarnings("ignore")
from astropy.io import ascii
import pandas as pd
Explanation: ApJdataFrames 008: Luhman2012
Title: THE DISK POPULATION OF THE UPPER SCORPIUS ASSOCIATION
Authors: K. L. Luhman and E. E. Mamajek
Data is from this paper:
http://iopscience.iop.org/0004-637X/7... |
13,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
quickcat calibration
This notebook is the quickcat calibration script.
- Its input is a redshift catalog merged with a target list and a truth table from simulations.
- Its output is a set o... | Python Code:
# input merged catalog (from simulations for now)
simulation_catalog_filename="/home/guy/Projets/DESI/analysis/quickcat/20180926/zcatalog-redwood-target-truth.fits"
# output quickcat parameter file that this code will write
quickcat_param_filename="/home/guy/Projets/DESI/analysis/quickcat/20180926/quickcat... |
13,108 | 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
def answer_one():
energy = pd.read_excel('Energy Indicators.xls', skiprows=18, skip_footer=38, header=None, na_values=['...'])
energy.drop([0,1], axis=1, inplace=True)
energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
energy['Energy... |
13,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Note especially the use of colons (
Step2: Notice the simplicity of the for loop
Step3: Note that the range starts at... | Python Code:
x = -15
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
This notebook c... |
13,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cable Property Comparison - 6/28/2016
This program reads a set of neuron hoc files from a given directory and spits out a tabular comparison of each neuron's cable properties; these properti... | Python Code:
# Required for system access (utilized below)
import sys
# Required for os access (utilized below)
import os
sys.path.append(os.path.join(os.path.dirname(os.getcwd()),
'dependencies'))
# Required to interpret hoc files
from neuron_readExportedGeometry import *
# Required for ef... |
13,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning a sensorimotor model with a sensorimotor context
In this notebook, we will see how to use the Explauto libarary to allow the learning and control of local actions that depend on a s... | Python Code:
from explauto.environment.simple_arm import SimpleArmEnvironment
from explauto.environment import environments
env_cls = SimpleArmEnvironment
env_conf = environments['simple_arm'][1]['low_dimensional']
Explanation: Learning a sensorimotor model with a sensorimotor context
In this notebook, we will see how ... |
13,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Processing
We need to make a column for average stats for each 'mon
We need to label each 'mon by its generation
(We should figure out a way to ignore non-stat changed formes i.e. Arceu... | Python Code:
mons["AVERAGE_STAT"] = mons["STAT_TOTAL"]/6
gens = pd.Series([0 for i in range(len(mons.index))], index=mons.index)
for ID, mon in mons.iterrows():
if 0<mon.DEXID<=151:
gens[ID] = 1
elif 151<mon.DEXID<=251:
gens[ID] = 2
elif 251<mon.DEXID<=386:
gens[ID] = 3
elif 386<... |
13,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
import time
import pylab as pl
from IPython import display
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
I... |
13,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The search for nearest-neighbors between (two) mock catalogs
As a first step in working over the cross-matching of two astronomical catalogs, below I experiment a nearest-neighbor (NN) metho... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import cm
import numpy
plt.rcParams['figure.figsize'] = (10.0, 10.0)
Explanation: The search for nearest-neighbors between (two) mock catalogs
As a first step in working over the cross-matching of two astronomical catalogs, below I ex... |
13,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2022 The TensorFlow Authors.
Step1: Composing Learning Algorithms
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: NOTE
Step5: ... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
13,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: encode fun
Step2: encode
Step3: we have an array of 25,000 rows and 10,000 columns. columns are words, rows are documents | Python Code:
import tensorflow as tf
import numpy as np
import pandas as pd
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=10000)
word_index = tf.keras.datasets.imdb.get_word_index()
word_index['fawn']
# why in the world it's indexed by word?
reverse_word_index = dict([(value,key) for... |
13,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Functions
Functions in Python work straight-forward
Step1: But what if we wanted to reuse this code to congratulate someone else, e.g. named Thomas? There's basically two (fundamentally dif... | Python Code:
print("Happy birthday to you.")
print("Happy birthday to you.")
print("Happy birthday, dear Chris.")
print("Happy birthday to you.")
Explanation: Functions
Functions in Python work straight-forward: They (optionally) require a set of inputs, perform some internal operations, and return a result. Now, we co... |
13,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load a thredds dataset
In the following example we will load a thredds dataset from the norwegian met.no thredds server.
Step1: The first step is to load the dataset. This will be performed... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pymepps
Explanation: Load a thredds dataset
In the following example we will load a thredds dataset from the norwegian met.no thredds server.
End of explanation
metno_path = 'http://thredds.met.no/thredds/dodsC/meps25files/' \
'meps_det_pp_2_5km... |
13,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The computation graph
TensorFlow programs are usually structured into a construction phase, that assembles a graph, and an execution phase that uses a session to execute ops in the graph.
Fo... | Python Code:
import tensorflow as tf
# Create a Constant op that produces a 1x2 matrix. The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])
# Create another Constant that produces a 2x1 matrix.
matrix2... |
13,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Chapter 1 - Getting Started with Variables and Values
This notebook uses code snippets and explanations from this course.
Welcome to the course! In this course we will... | Python Code:
%%capture
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip
!unzip Data.zip -d ../
!unzip images.zip -d .... |
13,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Downloading files to your local file system
files.download will invoke a browser download of the file to the user's local computer.
Step2: Google Drive
You can access... | Python Code:
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
Explanation: <a href="https://colab.research.google.com/github/termanli/CLIOL/blob/master/External_data_Driv... |
13,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Isosurface in volumetric data
Linear and nonlinear slices in volumetric data, as graphs of functions of two variables, were defined in this Jupyter Notebook http
Step1: We define an isosurf... | Python Code:
import plotly.graph_objs as go
import numpy as np
from skimage import measure
Explanation: Isosurface in volumetric data
Linear and nonlinear slices in volumetric data, as graphs of functions of two variables, were defined in this Jupyter Notebook http://nbviewer.jupyter.org/github/empet/Plotly-plots/blob/... |
13,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plug in dummy classifier
Step1: Use on classification model with exact method
Step2: Forest regressor model with estimated, exact, and recursive, using data
Works, though estimated is pre... | Python Code:
def f(array):
return (np.sum(X, axis=1) > 0.1).astype(float)
from sklearn.dummy import DummyRegressor
c = DummyRegressor()
c.fit(X, y)
c.predict = f
pdp, axes = partial_dependence.partial_dependence(c, [0, 1], X = X, method='exact')
Explanation: Plug in dummy classifier :
Works with a hack
End of expla... |
13,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 2
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: If we want to do any "feature engi... | Python Code:
import graphlab
Explanation: Regression Week 2: Multiple Regression (gradient descent)
In the first notebook we explored multiple regression using graphlab create. Now we will use graphlab along with numpy to solve for the regression weights with gradient descent.
In this notebook we will cover estimating ... |
13,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chempy
we will now introduce the Chempy function which will calculate the chemical evolution of a one-zone open box model
Step1: Loading all the input
solar abundances
SFR
infall
initial ab... | Python Code:
%pylab inline
# loading the default parameters
from Chempy.parameter import ModelParameters
a = ModelParameters()
Explanation: Chempy
we will now introduce the Chempy function which will calculate the chemical evolution of a one-zone open box model
End of explanation
# Initialising sfr, infall, elements to... |
13,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 2
Step1: Experiment parameters
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
Step2: Specify Nodes
Initiat... | Python Code:
from nilearn import plotting
%matplotlib inline
from os.path import join as opj
import json
from nipype.interfaces.spm import Level1Design, EstimateModel, EstimateContrast
from nipype.algorithms.modelgen import SpecifySPMModel
from nipype.interfaces.utility import Function, IdentityInterface
from nipype.in... |
13,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Who Is J?
Analysing JOTB diversity network
One of the main goals of the ‘Yes We Tech’ community is contributing to create an inclusive space where we can celebrate diversity, provide visibil... | Python Code:
import pandas as pd
import numpy as np
import scipy as sp
import pygal
import operator
from iplotter import GCPlotter
plotter = GCPlotter()
Explanation: Who Is J?
Analysing JOTB diversity network
One of the main goals of the ‘Yes We Tech’ community is contributing to create an inclusive space where we can ... |
13,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Determining whether a Javascript sample is malicious is not computable (https
Step1: Features | Python Code:
import glob
import string
import re
import numpy as np
# Loading the data
data = []
for js_file in glob.glob('Javascript/*/*'):
new = {}
new['name'] = js_file.split('/')[-1]
new['code'] = open(js_file,'r').read()
if new['name'][-2:] == 'js':
if new['name'][-6:] == 'min.js':
... |
13,129 | 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:
from collections import Counter
import numpy as np
import tensorflow as tf
from math import floor
with open('reviews.txt', 'r') as f:
reviews = f.read()
with open('labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement... |
13,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Object recognition with CNN
Keras is a Python library for deep learning that wraps the powerful numerical libraries Theano and TensorFlow.
A difficult problem where traditional neural networ... | Python Code:
# Plot ad hoc CIFAR10 instances
from keras.datasets import cifar10
from matplotlib import pyplot
# load data
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
Explanation: Object recognition with CNN
Keras is a Python library for deep learning that wraps the powerful numerical libraries Theano and... |
13,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
I swore to myself up and down that I wouldn't write one of these. But then I went and hacked up Pynads. And then I wrote a post on Pynads. And then I posted explainations about Monads on red... | Python Code:
x = y = ' Fred\n Thompson '
Explanation: I swore to myself up and down that I wouldn't write one of these. But then I went and hacked up Pynads. And then I wrote a post on Pynads. And then I posted explainations about Monads on reddit. So what the hell. I already fulfilled my "Write about decorators wh... |
13,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classify a Raster Using Threshold Values
In this tutorial, we will work with the NEON AOP L3 LiDAR ecoysystem structure (Canopy Height Model) data product. Refer to the links below for more ... | Python Code:
import numpy as np
import gdal, copy
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
Explanation: Classify a Raster Using Threshold Values
In this tutorial, we will work with the NEON AOP L3 LiDAR ecoysystem structure (Canopy Height Model) data product. ... |
13,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic factors and coincident indices
Factor models generally try to find a small number of unobserved "factors" that influence a subtantial portion of the variation in a larger number of o... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
np.set_printoptions(precision=4, suppress=True, linewidth=120)
from pandas.io.data import DataReader
# Get the datasets from FRED
start = '1979-01-01'
end = '2014-12-01'
indprod = DataRead... |
13,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kernel density estimation (KDE)
The following code has been adapted from Till A. Hoffmann.
See https
Step1: Unweighted, one-dimensional
Step2: Weighted, one-dimensional
Step3: Weighted, t... | Python Code:
%matplotlib inline
import os, sys
sys.path.append(os.path.abspath('../../main/python'))
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
import thalesians.tsa.distrs as distrs
import thalesians.tsa.kde as kde
import importlib
importlib.reload(distrs)
importlib.reload(kde)
Explanat... |
13,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP example
Step1: Deviation form thermal
Step2: Software version | Python Code:
%pylab inline
from qutip import *
import time
#number of states for each mode
N0=8
N1=8
N2=8
K=1.0
#damping rates
gamma0=0.1
gamma1=0.1
gamma2=0.4
alpha=sqrt(3)#initial coherent state param for mode 0
epsilon=0.5j #sqeezing parameter
tfinal=4.0
dt=0.05
tlist=arange(0.0,tfinal+dt,dt)
taulist=K*tlist #non-di... |
13,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Partial Differential Equations
If there's anything that needs serious computing power it's the solution of PDEs. However, you can go a long way to getting intuition on complex problems with ... | Python Code:
from __future__ import division
import numpy
from matplotlib import pyplot
%matplotlib notebook
dt = 1e-5
dx = 1e-2
x = numpy.arange(0,1+dx,dx)
y = numpy.zeros_like(x)
y = x * (1 - x)
def update_heat(y, dt, dx):
dydt = numpy.zeros_like(y)
dydt[1:-1] = dt/dx**2 * (y[2:] + y[:-2] - 2*y[1:-1])
ret... |
13,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
1. Installing Python
2. The Language
Expressions
List, Tuple and Dictionary
Strings
Functions
3. Example
Step1: To use the result of an expression in the future,
we a... | Python Code:
2 + 3 # Press <Ctrl-Enter to evaluate a cell>
2 + int(3.5 * 4) * float("8")
9 // 2 # Press <Ctrl-Enter to evaluate>
Explanation: Introduction to Python
1. Installing Python
2. The Language
Expressions
List, Tuple and Dictionary
Strings
Functions
3. Example: Word Frequency Analysis with Python
Reading text ... |
13,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
These graphs have all been produced according to appendix A of "Effect of GPS System Biases on Differential
Group Delay Measurements" available here
Step1: This plot is uncorrected, it is a... | Python Code:
files = glob("/home/greg/Documents/Summer Research/rinex files/ma*")
poop=rinexobs(files[6])
plt.figure(figsize=(14,14))
ax1 = plt.subplot(211)
ax1.xaxis.set_major_formatter(fmt)
plt.plot(2.85*(poop[:,23,'P2','data']*1.0E9/3.0E8-poop[:,23,'C1','data']*1.0E9/3.0E8)[10:],
'.',markersize=3,label='pr ... |
13,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding the most representative GWAS associated with cell-specific enhancers
(Execution on Google Cloud File System)
In this tutorial we are going to use a GWAS dataset (accessible from this... | Python Code:
%%bash
wget -q https://www.ebi.ac.uk/gwas/api/search/downloads/full -O tmp.tsv
cat tmp.tsv | \
awk 'BEGIN {FS="\t";OFS="\t"} {chrom=$12; gsub(chrom,"chr"chrom,$12)}{print $0}' | \
sed s/,//g > gwas.tsv
rm tmp.tsv
myBucket = "gs://fc-cad72548-2d6b-41ce-82aa-975cb7e8b764"
Explanation: Finding the mos... |
13,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anti-Aliasing Functions in Interferometry
Step1: Test setup
We will use a field of view of 0.004 radian. We place one
source within the field of view ($l=m=0.001$) and another 5 times stron... | Python Code:
%matplotlib inline
import sys
sys.path.append('../..')
from matplotlib import pylab
pylab.rcParams['figure.figsize'] = 12, 10
import numpy
import scipy
import scipy.special
from crocodile.clean import *
from crocodile.synthesis import *
from crocodile.simulate import *
from crocodile.antialias import *
fro... |
13,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Scientific Programming in Python</h1>
<h2 align="center">Topic 5
Step1: Table of Contents
1.- Cython Basic Usage
2.- Advanced usage
3.- Pure C in Python
<div id='cython' ... | Python Code:
%matplotlib inline
import numpy as np
import numexpr as ne
import numba
import math
import random
import matplotlib.pyplot as plt
import scipy as sp
import sys
%load_ext Cython
Explanation: <h1 align="center">Scientific Programming in Python</h1>
<h2 align="center">Topic 5: Accelerating Python with Cython:... |
13,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hyperparameters and Model Validation
<!--BOOK_INFORMATION-->
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
T... | Python Code:
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
Explanation: Hyperparameters and Model Validation
<!--BOOK_INFORMATION-->
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
The text is relea... |
13,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
La documentación necesaria para poder superar este ejercicio se encuentra en la documentación de ERPpeek
Tarea 1 - Conexión
Demuestra que sabes conectarte a una instancia de Odoo y listar to... | Python Code:
client = erppeek.Client(server=SERVER)
for database in client.db.list():
print('Base de datos: %r' % (database,))
Explanation: La documentación necesaria para poder superar este ejercicio se encuentra en la documentación de ERPpeek
Tarea 1 - Conexión
Demuestra que sabes conectarte a una instancia de Od... |
13,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building deep retrieval models
Learning Objectives
Converting raw input examples into feature embeddings.
Splitting the data into a training set and a testing set.
Configuring the deeper mod... | Python Code:
!pip install -q tensorflow-recommenders
!pip install -q --upgrade tensorflow-datasets
Explanation: Building deep retrieval models
Learning Objectives
Converting raw input examples into feature embeddings.
Splitting the data into a training set and a testing set.
Configuring the deeper model with losses and... |
13,145 | 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
Step2: The estimation game
Root mean squared error is one of several ways to summarize the average error of an estimation process.
... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import brfss
import thinkstats2
import thinkplot
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... |
13,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpretation and data acquisition strategies of seismic refraction data
In the <a href="https
Step1: Data
Below, we show 3 plots
Step2: Setup for the seismic refraction survey
Consider a... | Python Code:
plotWavelet()
Explanation: Interpretation and data acquisition strategies of seismic refraction data
In the <a href="https://www.3ptscience.com/app/SeismicRefraction">3pt Science app</a>, you explored the expected arrival times for refractions and reflections from a two-layer over a half-space model.
In t... |
13,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SciPy for Economists
Scipy provides many user-friendly and efficient numerical routines, e.g. numerical integration and optimization. The full documentation is available at http
Step1: Let ... | Python Code:
# standard library
import numpy as np
# Parametrization
num_agents = 1000
num_covars = 3
betas_true = np.array([0.22, 0.30, -0.1]).T
sd_true = 0.01
# Sampling of observables
np.random.seed(123)
X = np.random.rand(num_agents, num_covars)
X[:,0] = 1
# Sampling disturbances
eps = np.random.normal(loc=0.0, ... |
13,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Realistic example using outputs from MITgcm
This example requires the understanding of xgcm.grid and xmitgcm.open_mdsdataset.
Step1: One year of daily-averaged output from MITgcm.
Step2: D... | Python Code:
import numpy as np
import xarray as xr
import os.path as op
import xrft
from dask.diagnostics import ProgressBar
from xmitgcm import open_mdsdataset
from xgcm.grid import Grid
from matplotlib import colors, ticker
import matplotlib.pyplot as plt
%matplotlib inline
ddir = '/swot/SUM05/takaya/MITgcm/channel/... |
13,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook forms part of a series on computational optical radiometry. The notebooks can be downloaded from Github. These notebooks are constantly revised and updated, please revisit fro... | Python Code:
from IPython.display import display
from IPython.display import Image
from IPython.display import HTML
Explanation: This notebook forms part of a series on computational optical radiometry. The notebooks can be downloaded from Github. These notebooks are constantly revised and updated, please revisit from... |
13,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AdaptiveMD
Example 2 - Running of Tasks
Step1: Let's open our test project by its name. If you completed the previous example this should all work out of the box.
Step2: Open all connectio... | Python Code:
import sys, os
# stop RP from printing logs until severe
# verbose = os.environ.get('RADICAL_PILOT_VERBOSE', 'REPORT')
os.environ['RADICAL_PILOT_VERBOSE'] = 'ERROR'
from adaptivemd import (
Project,
Event, FunctionalEvent
)
from adaptivemd.engine.openmm import OpenMMEngine
from adaptivemd.analysis.... |
13,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An introduction to Gaussian Processes
Step1: The Gaussian Distribution
In this notebook, we'll go over the very basics of Gaussian Processes (GPs) and how to construct and draw samples from... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from matplotlib import rcParams
rcParams["figure.dpi"] = 100
rcParams["figure.figsize"] = 12, 4
Explanation: An introduction to Gaussian Processes
End of explanation
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
u = np... |
13,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantum SVM (variational method)
The QSVM_Kernel notebook here demonstrates a kernel based approach. This notebook shows a variational method.
For further information please see
Step1: Firs... | Python Code:
from datasets import *
from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit_aqua.input import get_input_instance
from qiskit_aqua import run_algorithm
Explanation: Quantum SVM (variational method)
The QSVM_Kernel notebook here demonstrates a kernel based appro... |
13,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Accessing and Plotting Meshes
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... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
Explanation: Accessing and Plotting Meshes
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 explanation
%matplot... |
13,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neal's funnel
This notebook introduces a toy distribution introduced by Radford Neal and is the $d+1$ dimensional,
$p(\boldsymbol{x},\nu) = \left[\prod_{i=1}^{d} \mathcal{N}(x_i|0,e^{\nu / 2... | Python Code:
import pints
import pints.toy
import numpy as np
import matplotlib.pyplot as plt
# Create log pdf
log_pdf = pints.toy.NealsFunnelLogPDF()
# Plot marginal density
levels = np.linspace(-7, -1, 20)
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
Z = [[log_pdf.marginal_log_... |
13,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Fold Quick Start
TensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors.
Step1: The basic elements of Fold are blocks. We'll start wi... | Python Code:
# boilerplate
import random
import tensorflow as tf
sess = tf.InteractiveSession()
import tensorflow_fold as td
Explanation: TensorFlow Fold Quick Start
TensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors.
End of explanation
scalar_block = td.Scalar()
vector3... |
13,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, ... |
13,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Create TensorFlow DNN model </h1>
This notebook illustrates
Step1: <h2> Create TensorFlow model using TensorFlow's Estimator API </h2>
<p>
First, write an input_fn to read the data.
St... | Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REG... |
13,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Effect of September-11 Terrorist Attack on Hate Crimes Against Muslims in the United Stateds
Course
Step1: Data Import (2005 - 2015)
Files for years 2005-2015 are available in excel format.... | Python Code:
import sys # system module
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for pandas
import reque... |
13,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
X Inactivation
I'd like to explore the state of genes on the X chromosome and see to what degree
the iPSCs reactivate their inactive Xs.
Step1: Inactivation for Single Sample
Let's take a l... | Python Code:
import cPickle
import datetime
import glob
import os
import random
import re
import subprocess
import cdpybio as cpb
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pybedtools as pbt
import scipy
import scipy.stats as stats
import seabor... |
13,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MapNode
If you want to iterate over a list of inputs, but need to feed all iterated outputs afterward as one input (an array) to the next node, you need to use a MapNode. A MapNode is quite ... | Python Code:
from nipype import Function
def square_func(x):
return x ** 2
square = Function(["x"], ["f_x"], square_func)
Explanation: MapNode
If you want to iterate over a list of inputs, but need to feed all iterated outputs afterward as one input (an array) to the next node, you need to use a MapNode. A MapNode ... |
13,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Writing Low-Level TensorFlow Code
Learning Objectives
Practice defining and performing basic operations on constant Tensors
Use Tensorflow's automatic differentiation capability
Learn how to... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.1 || pip install tensorflow==2.1
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
print(tf.__version__)
Explanation: Writ... |
13,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run from bootstrap paths
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 a... | Python Code:
%matplotlib inline
import openpathsampling as paths
import numpy as np
import math
# the openpathsampling OpenMM engine
import openpathsampling.engines.openmm as eng
Explanation: Run from bootstrap paths
Now we will use the initial trajectories we obtained from bootstrapping to run an MSTIS simulation. Thi... |
13,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab
Step1: Create Google Cloud Storage bucket for storing Vertex Pipeline artifacts
Step2: Import libraries
Step3: Create BigQuery dataset
Step4: Create BigQuery dataset for ML classific... | Python Code:
GOOGLE_CLOUD_PROJECT_ID = !(gcloud config get-value core/project)
GOOGLE_CLOUD_PROJECT_ID = GOOGLE_CLOUD_PROJECT_ID[0]
GOOGLE_CLOUD_REGION = 'us-central1'
BQ_DATASET_NAME = 'chicago_taxifare_tips'
BQ_TABLE_NAME = 'chicago_taxi_tips_ml'
BQ_LOCATION = 'US'
BQ_URI = f"bq://{GOOGLE_CLOUD_PROJECT_ID}.{BQ_DATASE... |
13,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Digit Recognizer
A BEGINNER'S GUIDE
Using
- Multi-layer Perceptron Model (MLP)
- Convolutional Neural Network (CNN) Model
- Keras
Import Libraries
Step1: Loading Train and Test datasets
Ste... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set() # setting seaborn default for plots
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
from keras.dataset... |
13,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background
Unlike Issue-Label Bot which predicts generic bug, feature-request and question labels, we are attempting to build the capability to predict repo-specific labels. One of the prim... | Python Code:
import pandas as pd
import numpy as np
from random import randint
from matplotlib import pyplot as plt
import re
pd.set_option('max_colwidth', 1000)
df = pd.read_csv('https://storage.googleapis.com/issue_label_bot/k8s_issues/000000000000.csv')
df.labels = df.labels.apply(lambda x: eval(x))
df.head()
#remov... |
13,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note to Amazon EC2 users
Step1: We also have a Python file containing implementations for several functions that will be used during the course of this assignment.
Step2: Load Wikipedia da... | Python Code:
import graphlab
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
assert (StrictVersion(graphlab.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'
Explanation: Note to Amazon EC2 users: To conserve memory, make sure to stop all the other no... |
13,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p class="note">
ReproduceIt is a series of articles that reproduce the results from data analysis articles focusing on having open data and open code.
</p>
Today as small return for the Rep... | Python Code:
%matplotlib inline
import pandas as pd
import os
data_dir = os.path.expanduser("~/data/names/names")
files = os.listdir(data_dir)
data = pd.DataFrame(columns=["year", "name", "sex", "occurrences"])
for fname in files:
if fname.endswith(".txt"):
fpath = os.path.join(data_dir, fname)
df =... |
13,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Polynomios
Step1: La clase poly1D representa polinomios unidimensionales con base en sus coeficientes. Sea el polinomio
$$ p(x) = 6 x^2 + x - 2 $$
su representación en NumPy es
Step2: Se p... | Python Code:
import numpy as np
Explanation: Polynomios
End of explanation
p = np.poly1d([6., 1., -2.])
Explanation: La clase poly1D representa polinomios unidimensionales con base en sus coeficientes. Sea el polinomio
$$ p(x) = 6 x^2 + x - 2 $$
su representación en NumPy es
End of explanation
p(0), p(1), p(10)
Explana... |
13,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
print(text)
Explanation: TV Script Generation
In this project, you'll generate your own Simpso... |
13,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encoder/Decoder Dialogue Management
Here we use a simple Encoder/Decoder GRU network to predict answers from the Cornell Movie-Dialog Corpus. We use PyTorch as a deep learning framework.
Mos... | Python Code:
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import string
import re
import random
from datetime import datetime
from collections import defaultdict
from six import iteritems
import numpy as np
import torch
import torch.nn as nn
from torch import ... |
13,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the two contig names you sent me it's simplest to do this
Step1: If you have a genuinely big file then I would do the following
Step2: Ya! There's two contigs. | Python Code:
desired_contigs = ['Contig' + str(x) for x in [1131, 3182, 39106, 110, 5958]]
desired_contigs
Explanation: Using the two contig names you sent me it's simplest to do this:
End of explanation
grab = [c for c in contigs if c.name in desired_contigs]
len(grab)
Explanation: If you have a genuinely big file the... |
13,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1
Step1: 2
Step2: 3
Step3: 4
Step4: 5
Step5: 6
Step6: 7
Step7: 8 | Python Code:
cat = True
dog = False
print(type(cat))
Explanation: 1: Booleans
Instructions
Assign the value True to the variable cat and the value False to the variable dog. Then use the print() function and the type() function to display the type for cat.
Answer
End of explanation
from cities import cities
print(citie... |
13,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(Introduction to Tensorflow) * 10^6
In this notebook, we modify the tensor-fied intro to TensorFlow notebook to use placeholder tensors and feed in data from a data set of millions of points... | Python Code:
import numpy as np
np.random.seed(42)
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf
tf.set_random_seed(42)
xs = np.linspace(0., 8., 8000000) # eight million points spaced evenly over the interval zero to eight
ys = 0.3*xs-0.8+np.random.normal(scale=0.25, siz... |
13,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 6
Step1: 2. a contourf map (of the first timestep) on a LambertConformal projection (with coastlines)
Step2: 3. a block plot (pcolormesh) map (of the first timestep) in its native... | Python Code:
qplt.contour(cube[:, 0])
plt.show()
Explanation: Exercise 6: Use the a1b sample data ('A1B_north_america.nc'), with appropriate slicing, to produce the following:
1. a contour plot of longitude vs time
End of explanation
import cartopy.crs as ccrs
ax = plt.axes(projection=ccrs.LambertConformal())
ax.coastl... |
13,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Secchi Disk
Overview
More information about Secchi DIsk can be found at
Step1: Step 1
Step2: Rotation of the image for an angle of t
Image Thresholding
Step3: Edge Detection
Edge detectio... | Python Code:
import os, sys
from os.path import expanduser
os.path
home = expanduser("~")
sys.path.append('/usr/local/Cellar/opencv/3.3.1_1/lib/python3.6/site-packages/')
sys.path.append(home + '/.pyenv/versions/OPENCV/lib/python3.6/site-packages/')
import cv2
cv2.__version__
! pip install numpy > tmp.log
! pip install... |
13,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
2. Mathematical Groundwork
Previous
Step1: Import section specific modules | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
2. Mathematical Groundwork
Previous: 2.11 Least-squares Minimization
Next: 2.13 Spherical Trigonometry
Import standard modules... |
13,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.algo - Calculer x**n le plus rapidement possible
C'est un exercice courant lors des entretiens d'embauche. Il faut savoir ce qu'est la dichotomie et la notation binaire d'un nombre.
Step1... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 1A.algo - Calculer x**n le plus rapidement possible
C'est un exercice courant lors des entretiens d'embauche. Il faut savoir ce qu'est la dichotomie et la notation binaire d'un nombre.
End of explanation
def puissance2k(x,k):
... |
13,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Fusion
Step1: Read in Data
Using GeoData we first have to get the data into the proper format. This example uses RISR data retrived from Madrigal, which can be read in by using the rea... | Python Code:
%matplotlib inline
import matplotlib
from __future__ import division,print_function
import logging
import pdb
import os
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import numpy as np
# Import Geodata modules
from GeoData import GeoData
from GeoData.plotting import slice2DGD,plot3Dslice... |
13,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Robust Linear Regression
This example has been lifted from the PyMC Docs, and adapted to for Bambi by Tyler James Burch (\@tjburch on GitHub).
Many toy datasets circumvent problems that prac... | Python Code:
import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
az.style.use("arviz-darkgrid")
np.random.seed(1111)
Explanation: Robust Linear Regression
This example has been lifted from the PyMC Docs, and adapted to for Bambi by Tyler James Burch (\@tjburch o... |
13,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We create two lingüistic variables, temperature and humidity. Those variables will contain five fuzzy set each.
Step1: Creamos dos variables lingüísticas de salida (output1, output2, cada u... | Python Code:
# Temperature sensor (range 0 to 40)
temperature = lvars.InputLVar('temperature', (10, 40))
temperature['MB'] = mfs.LineDescMF(10, 15)
temperature['B'] = mfs.TriMF(10, 18, 20)
temperature['N'] = mfs.TriMF(18, 20, 25)
temperature['A'] = mfs.TriMF(20, 25, 30)
temperature['MA'] = mfs.LineAscMF(25, 30)
# Humid... |
13,181 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Is it possible in PyTorch to change the learning rate of the optimizer in the middle of training dynamically (I don't want to define a learning rate schedule beforehand)? | Problem:
import numpy as np
import pandas as pd
import torch
optim = load_data()
for param_group in optim.param_groups:
param_group['lr'] = 0.0005 |
13,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style='background-image
Step1: 1. Initialization of setup
Step2: 2. The Mass Matrix
Now we initialize the mass and stiffness matrices. In general, the mass matrix at the elemental lev... | Python Code:
# Import all necessary libraries, this is a configuration step for the exercise.
# Please run it before the simulation code!
import numpy as np
import matplotlib.pyplot as plt
from gll import gll
from lagrange1st import lagrange1st
from ricker import ricker
# Show the plots in the Notebook.
plt.switch_bac... |
13,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aerospace Design via Quasiconvex Optimization
Consider a triangle, or a wedge, located within a hypersonic flow. A standard aerospace design optimization problem is to design the wedge to ma... | Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import math
x = np.linspace(.25,1,num=201)
obj = []
for i in range(len(x)):
obj.append(math.sqrt(1/x[i]**2-1))
plt.plot(x,obj)
import cvxpy as cp
x = cp.Variable(pos=True)
obj = cp.sqrt(cp.inv_pos(cp.square(x))-1)
p... |
13,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-3', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-3
Topic: Atmos
Sub-Topics: Dynamical ... |
13,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Monte Carlo method works by using random points to estimate ratios and values, the most basic example, shown here, is to calculate the value of $\pi$ by comparing the ratio of points in ... | Python Code:
#First, lets plot a circle, centered arround 0 with a radius of 1
plot_circle()
Explanation: The Monte Carlo method works by using random points to estimate ratios and values, the most basic example, shown here, is to calculate the value of $\pi$ by comparing the ratio of points in a circle with ones in th... |
13,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Linear Algebra - Inverse
Key Equation
Step1: Column-wise / Vectors (2x2)
We can also solve this equation in a vector way, by thinking of this as linear combination of two vectors
... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (10, 6)
x = np.arange(-10, 10, 1)
y1 = (15 - x)/3
y2 = (2 - 2*x)/-1
plt.plot(x, y1)
plt.text(x[-1], y1[-1], 'row1')
plt.plot(x, y2)
plt.text(x[-1], y2[-1], 'row2')
plt.axh... |
13,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play ... | Python Code:
import gym
import tensorflow as tf
import numpy as np
# Create the Cart-Pole game environment
env = gym.make('CartPole-v0')
Explanation: Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to tra... |
13,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimenting BQML and AutoML with Vertex AI
Overview
This notebook demonstrates how to use Vertex AI Pipelines to rapid prototype a model using both AutoML and BQML, do an evaluation compar... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
# Inst... |
13,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Previous
Step1: Its three main tables are vis.Session, vis.Condition, and vis.Trial. Furthermore vis.Condition has many tables below specifying parameters specific to each type of stimulus ... | Python Code:
%pylab inline
import datajoint as dj
from pipeline.vis import *
matplotlib.rcParams['figure.figsize'] = (10.0, 9.0)
Explanation: Previous: pipeline_experiment | Next: pipeline_preprocess
Schema vis
Schema pipeline.vis is upstream from preprocess and it contains information about the visual stimulus entered... |
13,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Now that I've streamlined the MCMC process, I am going to submit multiple chains simultaneously. This notebook will make multiple, similar config files, for broad comparison.
This ma... | Python Code:
import yaml
import copy
from os import path
import numpy as np
orig_cfg_fname = '/home/users/swmclau2/Git/pearce/bin/mcmc/nh_gg_sham_hsab_mcmc_config.yaml'
with open(orig_cfg_fname, 'r') as yamlfile:
orig_cfg = yaml.load(yamlfile)
orig_cfg
orig_sbatch_fname = '/home/users/swmclau2/Git/pearce/bin/mcmc/n... |
13,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SMA ROC Portfolio
1. The Security is above its 200-day moving average
2. The Security closes with sma_roc > 0, buy.
3. If the Security closes with sma_roc < 0, sell your long position.... | 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 inli... |
13,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clean UK schools data
This notebook cleans some UK schools data sets and joins them with other data sources as deprivation data.
Main datasets
Step1: Utility functions
Some utility function... | Python Code:
import pandas as pd
import numpy as np
Explanation: Clean UK schools data
This notebook cleans some UK schools data sets and joins them with other data sources as deprivation data.
Main datasets:
* gov.uk Comparing School Website
* English indices of deprivation 2015
End of explanation
def is_int(value):
... |
13,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
13,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring data
Step1: Salary
Replacing NA values with empty strings in the salary column
Step2: Extracting equity
Step3: Extracting currency and high - low salary
Need to extract currency... | Python Code:
jobs.columns
jobs.dtypes
jobs.describe()
jobs.head()
jobs.tail()
Explanation: Exploring data
End of explanation
jobs.salary = jobs.salary.fillna('')
Explanation: Salary
Replacing NA values with empty strings in the salary column
End of explanation
jobs['equity'] = jobs['salary'].str.contains('Provides Equi... |
13,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 1
Imports
Step3: Word counting
Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
Explanation: Algorithms Exercise 1
Imports
End of explanation
def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'):
Split a string into a list of words, removing punctuation and stop words.
s = ... |
13,196 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Right now, I have my data in a 3D numpy array. If I was to use MinMaxScaler fit_transform on each matrix of the array, it will normalize it column by column, whereas I wish to norma... | Problem:
import numpy as np
from sklearn.preprocessing import MinMaxScaler
a = np.array([[[1, 0.5, -2], [-0.5,1, 6], [1,1,1]], [[-2, -3, 1], [-0.5, 10, 6], [1,1,1]]])
scaler = MinMaxScaler()
result = np.zeros_like(a)
for i, arr in enumerate(a):
a_one_column = arr.reshape(-1, 1)
result_one_column = scaler.fit_tr... |
13,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Введение в численные методы оптимизации (Ю. Е. Нестеров Введение в выпуклую оптимизацию, гл. 1 $\S$ 1.1)
Обзор материала весеннего семестра
Постановка задачи
Общая схема решения
Сравнение ме... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
USE_COLAB = False
if not USE_COLAB:
plt.rc("text", usetex=True)
import numpy as np
C = 10
alpha = -0.5
q = 0.9
num_iter = 10
sublinear = np.array([C * k**alpha for k in range(1, num_iter + 1)])
linear = np.array([C * q**k for k in range(1, num_iter + 1... |
13,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Active Subspaces Example Function
Step1: First we draw M samples randomly from the input space.
Step2: Now we normalize the inputs, linearly scaling each to the interval $[-1, 1]$.
Step3: ... | Python Code:
import active_subspaces as ac
import numpy as np
%matplotlib inline
# The otlcircuit_functions.py file contains two functions: the circuit function (circuit(xx))
# and its gradient (circuit_grad(xx)). Each takes an Mx6 matrix (M is the number of data
# points) with rows being normalized inputs; circuit ret... |
13,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In-Class Coding Lab
Step1: Part 1
Step2: The request
As you learned in class and your assigned readings, the HTTP protocol has verbs which consititue the type of request you will send to t... | Python Code:
# Run this to make sure you have the pre-requisites!
!pip install -q requests
Explanation: In-Class Coding Lab: Understanding The Foundations of Web APIs
Overview
This lab covers the foundations of what is necessary to properly use consume HTTP web service API's with Python . Here's what we will cover.
Und... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.