Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basics
* algoritmos
* arquitectura
* funciones basicas
input, output, variables, while, for, if, def, vectores, diccionario, tupla y lista, graficacion
https
Step1: '''
Un número perfecto e... | Python Code:
import sys
print ('maximo float: ',sys.float_info.max)
print ('minimo float: ',sys.float_info.min)
print ('int: numero de bits por digito ',sys.int_info.bits_per_digit, 'esto es: ', 2**sys.int_info.bits_per_digit)
import matplotlib.pyplot as plt
import numpy as np
plt.close("all")
x=np.linspace(-10,10)
cua... |
14,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction using the top down (kmeans) method
This notebook details the process of prediction from which homework a notebook came after featurizing the notebook using the top down method. Th... | Python Code:
import sys
home_directory = '/dfs/scratch2/fcipollone'
sys.path.append(home_directory)
import numpy as np
from nbminer.notebook_miner import NotebookMiner
hw_filenames = np.load('../homework_names_jplag_combined_per_student.npy')
hw_notebooks = [[NotebookMiner(filename) for filename in temp[:59]] for temp ... |
14,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collecting and Using Data in Python
Laila A. Wahedi, PhD
Massive Data Institute Postdoctoral Fellow <br>McCourt School of Public Policy<br>
Follow along
Step1: Save more than one variable
S... | Python Code:
import pickle
mydata = [1,2,3,4,5,6,7,8,9,10]
pickle.dump(mydata, open('mydata.p','wb'))
Explanation: Collecting and Using Data in Python
Laila A. Wahedi, PhD
Massive Data Institute Postdoctoral Fellow <br>McCourt School of Public Policy<br>
Follow along:
Slides: http://Wahedi.us, Tutorial
Interactive Note... |
14,803 | 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
from __future__ import print_function
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.c... |
14,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute seed-based time-frequency connectivity in sensor space
Computes the connectivity between a seed-gradiometer close to the visual cortex
and all other gradiometers. The connectivity is... | Python Code:
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne import io
from mne.connectivity import spectral_connectivity, seed_target_indices
from mne.datasets import sample
from mne.time_frequency import AverageTFR
print(__doc__)
Explanation: Co... |
14,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #03-C
Keras API
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
Tutorial #02 showed how to implement a Convolutional Neural Network in TensorFlow.... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math
Explanation: TensorFlow Tutorial #03-C
Keras API
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
Tutorial #02 showed how to implement a Convolutional Neural Network in TensorFlo... |
14,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WGAN-GP with R-GCN for the generation of small molecular graphs
Author
Step1: Dataset
The dataset used in this tutorial is a
quantum mechanics dataset (QM9), obtained from
MoleculeNet. Alth... | Python Code:
from rdkit import Chem, RDLogger
from rdkit.Chem.Draw import IPythonConsole, MolsToGridImage
import numpy as np
import tensorflow as tf
from tensorflow import keras
RDLogger.DisableLog("rdApp.*")
Explanation: WGAN-GP with R-GCN for the generation of small molecular graphs
Author: akensert<br>
Date created:... |
14,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running on 4 cores with 30 gb RAM
Step1: Timing individual functions
Step2: Testing pipeline as a whole | Python Code:
import analysis3 as a3
reload(a3)
import time
def time_function(fun, *args):
start = time.time();
result = fun(*args);
run_time = time.time() - start;
minutes = run_time / 60;
print('RUN TIME: %f s (%f m)' % (run_time, minutes));
return result;
Explanation: Running on 4 cores with 3... |
14,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 3
Imports
Step1: Damped, driven nonlinear pendulum
The equations of motion for a simple pendulum of mass $m$, length $l$ are
Step4: Write a functio... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 3
Imports
End of explanation
g = 9.81 # m/s^2
l = 0.5 # length of pendul... |
14,809 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 1 - writing UDAFs the simple way
This small example shows how simple it could be to write a UDAF in Spark with moderate additions to the existing API. It takes the example published ... | Python Code:
# The main function
import karps as ks
# The standard library
import karps.functions as f
# Some tools to display the computation process:
from karps.display import show_phase
Explanation: Example 1 - writing UDAFs the simple way
This small example shows how simple it could be to write a UDAF in Spark with... |
14,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repetitive DNA elements ("repeats") are DNA sequences prevalent in genomes, especially of higher eukaryotes. Repeats make up about 50% of the human genome and over 80% of the maize genome. R... | Python Code:
import urllib.request
rm_site = 'http://www.repeatmasker.org'
fn = 'ce10.fa.out.gz'
url = '%s/genomes/ce10/RepeatMasker-rm405-db20140131/%s' % (rm_site, fn)
urllib.request.urlretrieve(url, fn)
import gzip
import itertools
fh = gzip.open(fn, 'rt')
for ln in itertools.islice(fh, 10):
print(ln, end='')
Ex... |
14,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameters used
Query profile size
Step1: 2. Helper methods
Step2: 2. Plot decay and noise | Python Code:
import matplotlib.lines as mlines
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
import json
%matplotlib inline
Explanation: Parameters used
Query profile size: 10
Number of query profiles: 5
Information Content: Annotation IC
Profile aggregation: Best Pairs
Di... |
14,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
练习 1:写函数,求n个随机整数均值的平方根,整数范围在m与k之间(n,m,k由用户输入)。
Step1: 写函数,共n个随机整数,整数范围在m与k之间,(n,m,k由用户输入)。求1:西格玛log(随机整数),2:西格玛1/log(随机整数)
Step2: 写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+... | Python Code:
m=int(input('请输入数字下界,按回车键结束'))
k=int(input('请输入数字上界,按回车键结束'))
n=int(input('请输入数字个数'))
i=0
import random
while i<n:
number=random.randint(m,k)
i+=1
print(number)
total=number+number+number
print((total/n)**(1/2))
Explanation: 练习 1:写函数,求n个随机整数均值的平方根,整数范围在m与k之间(n,m,k由用户输入)。
End of explanation
m=in... |
14,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
14,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brainstorm auditory tutorial dataset
Here we compute the evoked from raw for the auditory Brainstorm
tutorial dataset. For comparison, see [1]_ and
Step1: To reduce memory consumption and r... | Python Code:
# Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)
import os.path as op
import pandas as pd
import numpy as np
import mne
from mne import combine_evoked
from mne.minimum... |
14,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ploting points and lines on a reproject raster
Here's how to draw a line between seattle and portland given the raster modis image of Vancouver
produced by modis_to_h5.py
Note that this assu... | Python Code:
import h5py
from a301utils.a301_readfile import download
from mpl_toolkits.basemap import Basemap
from matplotlib import pyplot as plt
import json
import numpy as np
rad_file=' MYD021KM.A2016217.1915.006.2016218155919.h5'
geom_file='MYD03.A2016217.1915.006.2016218154759.h5'
download(rad_file)
data_name='MY... |
14,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Create an array of 10 zeros
Step2: Create an array of 10 ones
Step3: Create an array of 10 fives
Step4: Create an array of the integers from 10 to 50
Step5: Create ... | Python Code:
import numpy as np
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
<center>Copyright Pierian Data 2017</center>
<center>For more information, visit us at www.pieriandata.com</center>
NumPy Exercises - Solutions
Now that we've learned about NumPy let's test your... |
14,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: Preprocessing the data
However, since we are working with OpenCV, this time, we want to make sure the input
matrix is made up of 32-bit floatin... | Python Code:
from sklearn.datasets.samples_generator import make_blobs
X_raw, y_raw = make_blobs(n_samples=100, centers=2,
cluster_std=5.2, random_state=42)
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target... |
14,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brain-hacking 101
Author
Step1: Numpy arrays (ndarrays)
Creating a NumPy array is as simple as passing a sequence to np.array
Step2: You can create arrays with special generating functions... | Python Code:
import numpy as np
# Numpy is a package. To see what's in a package, type the name, a period, then hit tab
#np?
#np.
# Some examples of numpy functions and "things":
print(np.sqrt(4))
print(np.pi) # Not a function, just a variable
print(np.sin(np.pi)) # A function on a variable :)
Explanation: Brain-hack... |
14,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Impact of Terrorism on World Development
To explore our project with a lot more interaction and read our data story, visit our website!
Datasets description
Global Terrorism Database
This da... | Python Code:
import json
from urllib.request import urlopen
from urllib.parse import quote_plus
import pandas as pd
import numpy as np
from tqdm import tqdm_notebook
from multiprocessing import Pool, cpu_count
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pandas as pd
import sqlite3
import warnings
war... |
14,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Panel data sets
Step1: Panel Demographics
Panel demographic files have been standardized and are called ads demoN.csv, where
N is the year number
Step2: Store File
Naming convention
Step3:... | Python Code:
panel = pd.read_csv("IRI_Data//Year1/External/saltsnck/saltsnck_PANEL_DR_1114_1165.dat", delimiter="\t")
panel.head()
Explanation: Panel data sets: Category_PANEL_outlet_startweek_endweek.dat
Panel data is provided for two BehaviorScan markets, Eau Claire, Wisconsin and Pittsfield, Massachusetts.
The namin... |
14,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup Jupyter Notebook
Step1: cf. Examples for solve_ivp
Step2: An example for unit tests
cf. Runge-Kutta method from OK state
Depending on one's notation, for "stage" $s=4$, or $m=4$, the... | Python Code:
from pathlib import Path
import sys
notebook_directory_parent = Path.cwd().resolve().parent.parent
if str(notebook_directory_parent) not in sys.path:
sys.path.append(str(notebook_directory_parent))
%matplotlib inline
import numpy as np
import scipy
import sympy
from numpy import linspace
from scipy.int... |
14,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mpi-m', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MPI-M
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transport, E... |
14,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quadratic model
The quadratic model, pytransit.QuadraticModel, implements a transit over a stellar disk with the stellar limb darkening described using the quadratic limb darkening model as ... | Python Code:
%pylab inline
sys.path.append('..')
from pytransit import QuadraticModel
seed(0)
times_sc = linspace(0.85, 1.15, 1000) # Short cadence time stamps
times_lc = linspace(0.85, 1.15, 100) # Long cadence time stamps
k, t0, p, a, i, e, w = 0.1, 1., 2.1, 3.2, 0.5*pi, 0.3, 0.4*pi
pvp = tile([k, t0, p, a, i, e... |
14,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Session 4
Step2: <a name="part-1---pretrained-networks"></a>
Part 1 - Pretrained Networks
In the libs module, you'll see that I've included a few modules for loading some state of th... | Python Code:
# First check the Python version
import sys
if sys.version_info < (3,4):
print('You are running an older version of Python!\n\n',
'You should consider updating to Python 3.4.0 or',
'higher as the libraries built for this course',
'have only been tested in Python 3.4 and hi... |
14,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Visualization with Altair
Author
Step1: Other libraries
Import other libraries used in this notebook.
pandas
Step4: Region reduction function
Reduction of pixels intersecting t... | Python Code:
import ee
ee.Authenticate()
ee.Initialize()
Explanation: Time Series Visualization with Altair
Author: jdbcode
This tutorial provides methods for generating time series data in Earth Engine and visualizing it with the Altair library using drought and vegetation response as an example.
Topics include:
Time ... |
14,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyphysio tutorial
2. Algorithms
In this second tutorial we will see how to use the class Algorithm to create signal processing pipelines.
A signal processing step is a computational function... | Python Code:
# import packages
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# import data from included examples
from pyphysio.tests import TestData
from pyphysio import EvenlySignal
ecg_data = TestData.ecg()
eda_data = TestData.eda()
# create two signals
fsamp =... |
14,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
02 - Data from the Web
Deadline
Wednesday October 25, 2017 at 11
Step1: www.topuniversities.com
Step2: Best universities in term of
Step3: Comments
Step4: Comments
Step5: Comments
Step6... | Python Code:
import requests, re, html
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
from tqdm import tqdm_notebook
import warnings
warnings.filterwarnings('ignore')
NUM_OBS = 200
Explanation: 02 - Data from the Web
Deadline
Wednesday October ... |
14,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure
Step1: 1. What is the voxelwise threshold?
Step2: 2. Definition of alternative
Detect 1 region
We define a 'success' as a situation in which the maximum in the active field exceeds
... | Python Code:
% matplotlib inline
from __future__ import division
import os
import nibabel as nib
import numpy as np
from neuropower import peakdistribution
import scipy.integrate as integrate
import pandas as pd
import matplotlib.pyplot as plt
import palettable.colorbrewer as cb
if not 'FSLDIR' in os.environ.keys():
... |
14,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
test netcdf+
This is a more extensive integration test, if all the features of netcdf+ work as expected.
Step1: Open new storage
try to create a new storage
Step2: Create some stores
Step3... | Python Code:
import openpathsampling as paths
from openpathsampling.netcdfplus import (
NetCDFPlus,
ObjectStore,
StorableObject,
NamedObjectStore,
UniqueNamedObjectStore,
DictStore,
ImmutableDictStore,
VariableStore,
StorableNamedObject
)
import numpy as np
from __future__ import p... |
14,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note that the sequence size Nzc is lower then the number of subcarriers that will have elements of the Zadoff-Chu sequence. That is $Nzc \leq 300/2 = 150$. Therefore, we will append new elem... | Python Code:
# Create root sequence objects
a_u1 = RootSequence(u1, size=Nsc//2, Nzc=Nzc)
a_u2 = RootSequence(u1, size=Nsc//2, Nzc=Nzc)
a_u3 = RootSequence(u1, size=Nsc//2, Nzc=Nzc)
Explanation: Note that the sequence size Nzc is lower then the number of subcarriers that will have elements of the Zadoff-Chu sequence. T... |
14,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Market Environment and Portfolio Object
We start by instantiating a market environment object which in particular contains a list of ticker symbols in which we are int... | Python Code:
from dx import *
from pylab import plt
plt.style.use('seaborn')
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Mean-Variance Portfolio Class
Without doubt, the Markowitz (1952) mean-variance portfolio theory is a cornerstone of modern ... |
14,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem 1
Write a function that takes a list of 0s and 1s and produces the corresponding integer. The equation for converting a list $L = [l_1, l_2, ..., l_n]$ of 0's and 1's to binary is $\... | Python Code:
def to_binary(x):
the_sum = 0
# enumerate returns pairs of values from `x`
# as well as the index of each value
for index, value in enumerate(x):
the_sum += value * 2**index
return the_sum
my_list = [1, 1]
to_binary(my_list)
my_list = [1, 0, 0, 0, 1, 1, 0, 1]
to_binary(my_l... |
14,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
readwrite module pgmpy
pgmpy is a python library for creation, manipulation and implementation of Probabilistic graph models. There are various standard file formats for representing PGM dat... | Python Code:
from pgmpy.readwrite import ProbModelXMLReader
reader_string = ProbModelXMLReader('../files/example.pgmx')
Explanation: readwrite module pgmpy
pgmpy is a python library for creation, manipulation and implementation of Probabilistic graph models. There are various standard file formats for representing PGM ... |
14,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Step1: Warm-up exercises
Exercise
Step2: Exercise
Step3: Exercise
Step4: Exercise
Step8: The Boston Bruins problem
The Hockey suite contains hypotheses about the goal scorin... | Python Code:
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Joint
import thinkplot
Explanation: Think Bayes: Chapter 7
This notebook presents code and exercises from Think Bayes... |
14,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IST256 Lesson 10
HTTP and Network Programming
Assigned Readings From
https
Step1: A. str
B. int
C. dict
D. list
Vote Now
Step2: A. str
B. int
C. dict
D. list
Vote Now
Step3: A. 2
B.... | Python Code:
x = { 'a' : [1,2,3,4], 'b' : 'rta', 'c': { 'r' : 3, 't' : 2} }
print( type(x['a']) )
Explanation: IST256 Lesson 10
HTTP and Network Programming
Assigned Readings From
https://ist256.github.io/spring2021/readings/Web-APIs-In-Python.html
Links
Participation: https://poll.ist256.com
In-Class Questions: ZOOM... |
14,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference with GPs
The dataset needed for this worksheet can be downloaded. Once you have downloaded s9_gp_dat.tar.gz, and moved it to this folder, execute the following cell
Step4: Here ar... | Python Code:
!tar -zxvf s9_gp_dat.tar.gz
!mv *.txt data/
Explanation: Inference with GPs
The dataset needed for this worksheet can be downloaded. Once you have downloaded s9_gp_dat.tar.gz, and moved it to this folder, execute the following cell:
End of explanation
import numpy as np
from scipy.linalg import cho_factor
... |
14,837 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Geospatial Analysis
One of the most popular extensions to PostgreSQL is PostGIS,
which adds support for storing geospatial geometries,
as well as functionality for reasoning about and perfor... | Python Code:
# Launch the postgis container.
# This may take a bit of time if it needs to download the image.
!docker run -d -p 5432:5432 --name postgis-db -e POSTGRES_PASSWORD=supersecret mdillon/postgis:9.6-alpine
Explanation: Geospatial Analysis
One of the most popular extensions to PostgreSQL is PostGIS,
which adds... |
14,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
from SciPy, scipy.linalg.svd - Singular Value Decomposition using SciPy
cf. scip.linalg.svd
Factorizes the matrix a into 2 unitary matrices U and Vh, and a 1-d. array s of singular values (r... | Python Code:
import numpy as np
from scipy import linalg
# Create an array of the given shape and populate it with
# random samples from a uniform distribution
# over ``[0, 1)``.
a = np.random.randn(9,6) + 1.j * np.random.randn(9,6)
a
U, s, Vh = linalg.svd(a)
U.shape, Vh.shape, s.shape
U
Vh
s
Explanation: from Sc... |
14,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
← Back to Index
Jupyter Audio Basics
Audio Libraries
We will mainly use two libraries for audio acquisition and playback
Step1: Visit https
Step2: If you receive an error with librosa... | Python Code:
ls audio
Explanation: ← Back to Index
Jupyter Audio Basics
Audio Libraries
We will mainly use two libraries for audio acquisition and playback:
1. librosa
librosa is a Python package for music and audio processing by Brian McFee. A large portion was ported from Dan Ellis's Matlab audio processing exa... |
14,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Right now, each data point consists of two strings and an integer label. Computers don't like dealing with strings directly very much, so we need to convert these strings to lists of integer... | Python Code:
padding_token = "@@PADDING@@"
oov_token = "@@UNKOWN@@"
word_indices = {padding_token: 0, oov_token: 1}
for train_instance in tqdm(raw_train_lines):
# unpack the tuple into 3 variables
question_1, question_2, label = train_instance
# iterate over the tokens in each question, and add them to the ... |
14,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poster popularity by country
This notebook loads data of poster viewership at the SfN 2016 annual meeting, organized by the countries that were affiliated with each poster.
We find that the ... | Python Code:
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
import pandas as pd
# Load data
df = pd.DataFrame.from_csv('./posterviewers_by_country.csv')
key_N = 'Number of people'
Explan... |
14,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mri', 'mri-esm2-0', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MRI
Source ID: MRI-ESM2-0
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
14,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quickstart
This is a short introduction and quickstart for the PySpark DataFrame API. PySpark DataFrames are lazily evaluated. They are implemented on top of RDDs. When Spark transforms data... | Python Code:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
Explanation: Quickstart
This is a short introduction and quickstart for the PySpark DataFrame API. PySpark DataFrames are lazily evaluated. They are implemented on top of RDDs. When Spark transforms data, it does not immediatel... |
14,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
26 Maximum Flow
each directed edge in a flow network like a conduit for the material
Step1: 26.2 The Ford-Fulkerson method
The Ford-Fulkerson method depends on three important ideas
Step2: ... | Python Code:
plt.imshow(plt.imread('./res/fig26_1.png'))
# Exercise
Explanation: 26 Maximum Flow
each directed edge in a flow network like a conduit for the material: Each conduit has a stated capacity, vertices are conduit junctions.
In the maximum-flow problem, we wish to compute the greatest rate at which we can shi... |
14,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thanks to unicode, we may use Greek letters directly in our code.
In this Jupyter Notebook, lets use θ (theta), π (pi) and τ (tau) with τ = 2 * π.
Then we'll plot the graph of Euler's Fo... | Python Code:
from math import e, pi as π
τ = 2 * π
i = 1j
result = e ** (i * τ)
print ("{:1.5f}".format(result.real))
Explanation: Thanks to unicode, we may use Greek letters directly in our code.
In this Jupyter Notebook, lets use θ (theta), π (pi) and τ (tau) with τ = 2 * π.
Then we'll plot the graph of Euler's F... |
14,846 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a binary array, say, a = np.random.binomial(n=1, p=1/2, size=(9, 9)). I perform median filtering on it using a 3 x 3 kernel on it, like say, b = nd.median_filter(a, 3). I wou... | Problem:
import numpy as np
import scipy.ndimage
a= np.zeros((5, 5))
a[1:4, 1:4] = np.arange(3*3).reshape((3, 3))
b = scipy.ndimage.median_filter(a, size=(3, 3), origin=(0, 1)) |
14,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Core Techniques used in our ETL
Generators
Partial function application
Batching / Chunking
Caching
Step1: Generators
python generators allow you to concisely create iterators.
They are a h... | Python Code:
import collections
import functools
import more_itertools
import json
Explanation: Core Techniques used in our ETL
Generators
Partial function application
Batching / Chunking
Caching
End of explanation
# start with a function that produces a list of squared numbers
def squares_as_list(max_n):
accum = [... |
14,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Bubble sort
In pseudo-code the bubble sort algorithm can be written as
Step2: We can see the essential features of Python used
Step4: Note
Step6: This gets rid of the need for a te... | Python Code:
def bubblesort(unsorted):
Sorts an array using bubble sort algorithm
Paramters
---------
unsorted : list
The unsorted list
Returns
sorted : list
The sorted list (in place)
last = len(unsorted)
# All Python lists start from 0... |
14,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this notebook, we will demonstrate how Google Sheets can be used as a simple medium for managing, updating, and evaluating Intents and Training Phrases in Dialogflow CX.
Spec... | Python Code:
#If you haven't already, make sure you install the `dfcx-scrapi` library
!pip install dfcx-scrapi
Explanation: Introduction
In this notebook, we will demonstrate how Google Sheets can be used as a simple medium for managing, updating, and evaluating Intents and Training Phrases in Dialogflow CX.
Specifical... |
14,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step1: Unit Test | Python Code:
%run ../stack/stack.py
%load ../stack/stack.py
class QueueFromStacks(object):
def __init__(self):
# TODO: Implement me
pass
def shift_stacks(self, source, destination):
# TODO: Implement me
pass
def enqueue(self, data):
# TODO: Implement me
pass
... |
14,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python Steering
The following is a tour of the basic layout of CRPropa 3, showing how to setup and run a 1D simulation of the extragalactic propagation of UHECR protons from ... | Python Code:
from crpropa import *
# simulation: a sequence of simulation modules
sim = ModuleList()
# add propagator for rectalinear propagation
sim.add(SimplePropagation())
# add interaction modules
sim.add(PhotoPionProduction(CMB()))
sim.add(ElectronPairProduction(CMB()))
sim.add(NuclearDecay())
sim.add(MinimumEnerg... |
14,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial Part 23
Step1: Make The Datasets
Let's begin by loading some molecules to work with. We load Tox21, specifying splitter=None so everything will be returned as a single dataset.
St... | Python Code:
!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import conda_installer
conda_installer.install()
!/root/miniconda/bin/conda info -e
!pip install --pre deepchem
import deepchem
deepchem.__version__
Explanation: Tutorial Part 23: Synthetic Feas... |
14,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example plot for LFPy
Step1: Function declaration
Step2: Parameters etc.
Step3: Main simulation procedure
Step4: Plot | Python Code:
# importing some modules, setting some matplotlib values for pl.plot.
import LFPy
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size' : 12,
'figure.facecolor' : '1',
'figure.subplot.wspace' : 0.5,
'figure.subplot... |
14,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Patrick provided a pair of images from AuxTel.
Let's look at how those images work with our cwfs code
load the modules
Step1: Define the image objects. Input arguments
Step2: Define the in... | Python Code:
from lsst.cwfs.instrument import Instrument
from lsst.cwfs.algorithm import Algorithm
from lsst.cwfs.image import Image, readFile, aperture2image, showProjection
import lsst.cwfs.plots as plots
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Patrick provided a pair of ima... |
14,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Access TTree in Python using PyROOT and fill a histogram
<hr style="border-top-width
Step1: Optional
Step2: Open a file which is located on the web. No type is to be specified for "f".
Ste... | Python Code:
import ROOT
Explanation: Access TTree in Python using PyROOT and fill a histogram
<hr style="border-top-width: 4px; border-top-color: #34609b;">
First import the ROOT Python module.
End of explanation
%jsroot on
Explanation: Optional: activate the JavaScript visualisation to produce interactive plots.
End ... |
14,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aufgabe 4
Step1: a) We load the breast cancer data set.
Step2: b) We split the data into features X and labels y. After that we transform the binary labels to numerical values.
Step3: c) ... | Python Code:
# imports
import pandas
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from s... |
14,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Empirically Matching OM10 Lens Galaxies to SL2S
Phil Marshall & Bryce Kalmbach, September 2016
Last Updated
Step1: Set the CosmoDC2 catalog you want to use here and this will ensure consist... | Python Code:
import numpy as np
import matplotlib as mpl
mpl.rcParams['text.usetex'] = False
from matplotlib import pyplot as plt
import corner
import urllib
import os
from sklearn.cross_validation import train_test_split
from astroML.plotting import setup_text_plots
from lsst.sims.photUtils import Sed, Bandpass, Bandp... |
14,858 | Given the following text description, write Python code to implement the functionality described.
Description:
Minimum number of increment / decrement operations such that array contains all elements from 1 to N
Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i +... | Python Code:
def minimumMoves(a , n ) :
operations = 0
a . sort(reverse = False )
for i in range(0 , n , 1 ) :
operations = operations + abs(a[i ] -(i + 1 ) )
return operations
if __name__== ' __main __' :
arr =[5 , 3 , 2 ]
n = len(arr )
print(minimumMoves(arr , n ) )
|
14,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NOAA Weather Analysis
Frequency of Daily High and Low Record Temperatures
Analysis
Goal
Given historical data for a weather station in the US, what is the frequency for new high or low tempe... | Python Code:
%matplotlib inline
import os
import struct
import glob
import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
import seaborn as sns
import folium
from IPython.display import HTML
from IPython.display import Javascript, display
Explanation: NOAA Weather Analysis
Frequen... |
14,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Beautiful JavaScript Charts in Jupyter Notebooks
Jupyter Notebooks tell stories by blending explanations, visualizations, and the code producing them. In my opinion, the most compelling char... | Python Code:
import iplotter
from IPython.core.display import HTML
Explanation: Beautiful JavaScript Charts in Jupyter Notebooks
Jupyter Notebooks tell stories by blending explanations, visualizations, and the code producing them. In my opinion, the most compelling charts are interactive, Javascript based. Here's how y... |
14,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In these exercises, you'll explore the operations a couple of popular convnet architectures use for feature extraction, learn about how convnets can capture large-scale visual f... | Python Code:
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.computer_vision.ex4 import *
import tensorflow as tf
import matplotlib.pyplot as plt
import learntools.computer_vision.visiontools as visiontools
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='b... |
14,862 | 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', 'miroc', 'miroc-es2l', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MIROC
Source ID: MIROC-ES2L
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, E... |
14,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Timeseries
Overview. We introduce the tools for working with dates, times, and time series data. We start with functionality built into python itself, then discuss how pandas builds on thes... | 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
%matplotlib inline
plt.style.use("ggplot")
# quandl pa... |
14,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vortex sheets
Our numerical method for 2D-potential flow will be developed using vortex sheets. In this first lesson, we derive the equations for a simple vortex sheet and plot the velocity ... | Python Code:
import numpy
N = 30 # number of points along each axis
X = numpy.linspace(-2, 2, N) # computes a 1D-array for x
Y = numpy.linspace(-2, 2, N) # computes a 1D-array for y
x, y = numpy.meshgrid(X, Y) # generates a mesh grid
Explanation: Vortex sheets
Our numerical method for... |
14,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Style Transfer
In this notebook we will implement the style transfer technique from "Image Style Transfer Using Convolutional Neural Networks" (Gatys et al., CVPR 2015).
The general idea is ... | Python Code:
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision
import torchvision.transforms as T
import PIL
import numpy as np
from scipy.misc import imread
from collections import namedtuple
import matplotlib.pyplot as plt
from cs231n.image_utils import SQUEEZENET_MEAN, SQUEEZE... |
14,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 20 - Tables and Networks
In the previous chapter we looked into various types of charts and correlations that are useful for scientific analysis in Python. Here, we present two more ... | Python Code:
%matplotlib inline
Explanation: Chapter 20 - Tables and Networks
In the previous chapter we looked into various types of charts and correlations that are useful for scientific analysis in Python. Here, we present two more groups of visualizations: tables and networks. We will spend little attention to thes... |
14,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first presentation
Import Beampy
To start, you need to import beampy module in your python file.
.. code-block
Step1: Change the position of the text element
By default the text elemen... | Python Code:
from beampy import *
# We first create a new document for our presentation
# Remove quiet=True to see Beampy compiler output
doc = document(quiet=True)
# Then we create a new slide with the title "My first new slide"
with slide('My first slide title'):
# All the slide contents are functions added insid... |
14,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content and Objectives
Show transmission signals and spectra of BPSK and OOK
Random data (and thus random signals) are generated, spectra being estimated by averaging
Import
Step1: Paramete... | Python Code:
# importing
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=matplotlib.checkdep_usetex(True))
matplotlib.rc('figure', figsize=(14, 6) )
Explanation: Conte... |
14,869 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Partial Fraction Expansion using Sympy
This is an example for using partial fraction expansion within Python
This only covers a tiny fraction of what is possible.
As always it's a good idea... | Python Code:
import sympy
import numpy as np
sympy.init_printing()
Explanation: Partial Fraction Expansion using Sympy
This is an example for using partial fraction expansion within Python
This only covers a tiny fraction of what is possible.
As always it's a good idea to look at the documentation
http://docs.sympy.o... |
14,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 15
Step1: Example 2
Step2: The previous step constructs a log-linear approximation of the model and then solves for the endogenous variables as functions of the state variables and e... | Python Code:
# 1. Input model parameters
parameters = pd.Series()
parameters['rhoa'] = .9
parameters['sigma'] = 0.001
print(parameters)
# 2. Define a function that evaluates the equilibrium conditions
def equilibrium_equations(variables_forward,variables_current,parameters):
# Parameters
p = parameters
... |
14,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Data
Step2: Create A Linear
Step3: View Results
Step4: View Percentage Of Variance Retained By New Features | Python Code:
# Load libraries
from sklearn import datasets
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
Explanation: Title: Using Linear Discriminant Analysis For Dimensionality Reduction
Slug: lda_for_dimensionality_reduction
Summary: How to use linear discriminant analysis for dimensionality... |
14,872 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a 2-dimensional numpy array which contains time series data. I want to bin that array into equal partitions of a given length (it is fine to drop the last partition if it is ... | Problem:
import numpy as np
data = np.array([[4, 2, 5, 6, 7],
[ 5, 4, 3, 5, 7]])
bin_size = 3
new_data = data[:, ::-1]
bin_data_mean = new_data[:,:(data.shape[1] // bin_size) * bin_size].reshape(data.shape[0], -1, bin_size).mean(axis=-1)[:,::-1] |
14,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Secton 6.5.
The Dalem pumping test (semi-confined, Hantush type)
IHE, Transient groundwater
Olsthoorn, 2019-01-03
The most famous book on pumping test analyses is due to Krusemand and De Ri... | Python Code:
from scipy.special import exp1
import numpy as np
import matplotlib.pyplot as plt
Explanation: Secton 6.5.
The Dalem pumping test (semi-confined, Hantush type)
IHE, Transient groundwater
Olsthoorn, 2019-01-03
The most famous book on pumping test analyses is due to Krusemand and De Ridder (1970, 1994). The... |
14,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
p-Hacking and Multiple Comparisons Bias
By Delaney Mackenzie and Maxwell Margenot.
Part of the Quantopian Lecture Series
Step1: Refresher
Step2: If we add some noise our coefficient will d... | Python Code:
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
Explanation: p-Hacking and Multiple Comparisons Bias
By Delaney Mackenzie and Maxwell Margenot.
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
github.com/quantopian/research_public
Noteboo... |
14,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Theano 패키지 소개
Theano 패키지는 GPU를 지원하는 선형 대수 심볼 컴파일러(Symbolic Linear Algebra Compiler)이다.
심볼 컴파일러란 수치적인 미분, 선형 대수 계산 뿐 아니라 symbolic expression을 통해 정의된 수식(주로 목적 함수)을 사람처럼 미분하거나 재정리하여 전체 계산에 대한 최... | Python Code:
import theano
import theano.tensor as T #벡터에서 차원 늘어나면 metrix. 거기서 차원 늘어나면 tensor라고 한다.
from theano import function
x = T.dscalar('x') #d는 double. float 타입
y = T.dscalar('y')
type(x), type(y)
Explanation: Theano 패키지 소개
Theano 패키지는 GPU를 지원하는 선형 대수 심볼 컴파일러(Symbolic Linear Algebra Compiler)이다.
심볼 컴파일러란 수치적... |
14,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Ames Housing dataset was compiled by Dean De Cock for use in data science education. It's an incredible alternative for data scientists looking for a modernized and expanded version of t... | Python Code:
import pandas as pd
from supervised.automl import AutoML
from supervised.preprocessing.eda import EDA
Explanation: The Ames Housing dataset was compiled by Dean De Cock for use in data science education. It's an incredible alternative for data scientists looking for a modernized and expanded version of the... |
14,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Express Deep Learning in Python - Part 1
Do you have everything ready? Check the part 0!
How fast can you build a MLP?
In this first part we will see how to implement the basic components of... | Python Code:
import numpy
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.datasets import mnist
Explanation: Express Deep Learning in Python - Part 1
Do you have everything ready? Check the part 0!
How fast can you build a MLP?
In this first part we will see how to im... |
14,878 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute a sparse inverse solution using the Gamma-Map empirical Bayesian method
See [1]_ for details.
References
.. [1] D. Wipf, S. Nagarajan
"A unified Bayesian framework for MEG/EEG sou... | Python Code:
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.inverse_sparse import gamma_map, make_stc_from_dipoles
from mne.viz import (plot_sparse_sour... |
14,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análisis de los datos obtenidos
Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción. Los datos analizados son del filamento de bq el día 20 de Julio del 201... | Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn as sk
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
#Mostramos las versiones usadas de cada librerías
pri... |
14,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 4
Step1: Example 1
Step2: Next we set up an instance of NPTFit and add in the data. We'll analyze the entire sky at once, so we won't add in a mask.
Step3: Now we add in templates... | Python Code:
# Import relevant modules
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
from matplotlib import rcParams
from NPTFit import nptfit # module for performing scan
from NPTFit import dnds_analysis # module for analysing the output
fr... |
14,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hospital readmissions data analysis and recommendations for reduction
Background
In October 2012, the US government's Center for Medicare and Medicaid Services (CMS) began reducing Medicare ... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import bokeh.plotting as bkp
from mpl_toolkits.axes_grid1 import make_axes_locatable
%matplotlib inline
# read in readmissions data provided
hospital_read_df = pd.read_csv('data/cms_hospital_readmissions.csv')
Explanation: Hospital read... |
14,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Checking-tool" data-toc-modified-id="Checking-tool-1"><span class="toc-item-... | Python Code:
from skidl.pyspice import *
from PySpice.Spice.Netlist import Circuit
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Checking-tool" data-toc-modified-id="Checking-tool-1"><span class="toc-item-num">1 </span>Checking ... |
14,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 8
Problem 8-10 to Problem 8-11
Step1: Description
| | |
|--... | Python Code:
%pylab notebook
%precision %.4g
Explanation: Excercises Electric Machinery Fundamentals
Chapter 8
Problem 8-10 to Problem 8-11
End of explanation
P_rated = 30 # [hp]
Il_rated = 110 # [A]
Vt = 240 # [V]
Nf = 2700
n_0 = 1800 # [r/min]
Nse = 14
Ra = 0.19 # [Ohm]
Rf = ... |
14,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
European Extremely Large Telescope site selection
a comparison between real selection and multicriteria-decision-analysis suggestions
Juan B Cabral – Bruno O Sanchez – Manuel Starck Cuffini... | Python Code:
import pandas as pd
import numpy as np
import skcriteria as sc
from skcriteria.madm import topsis, wsum, moora, wprod, electre
df = pd.read_csv("sites.csv")[:-3]
df
anames = df.columns[2:].values
def to_apply(r):
new = []
for e in r:
if isinstance(e , str):
e = float(e.replace("... |
14,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Designing a Python library for building prototypes around MinHash
This is very much work-in-progress. May be the software and or ideas presented with be the subject of a peer-reviewed or sel... | Python Code:
# we take a DNA sequence as an example, but this is arbitrary and not necessary.
alphabet = b'ATGC'
# create a lookup structure to go from byte to 4-mer
# (a arbitrary byte is a bitpacked 4-mer)
quad = [None, ]*(len(alphabet)**4)
i = 0
for b1 in alphabet:
for b2 in alphabet:
for b3 in alphabet:... |
14,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data poisoning attack
In this notebook, we use a convex optimization layer to perform a data poisoning attack; i.e., we show how to perturb the data used to train a logistic regression class... | Python Code:
import cvxpy as cp
import matplotlib.pyplot as plt
import numpy as np
import torch
from cvxpylayers.torch import CvxpyLayer
Explanation: Data poisoning attack
In this notebook, we use a convex optimization layer to perform a data poisoning attack; i.e., we show how to perturb the data used to train a logis... |
14,887 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing an <span style="font-variant
Step1: Note that this grammar does not contain any embedded actions.
Hence we cannot compute anything with it. We will only be able to
check whether a... | Python Code:
!cat -n Expr.g4
!type Expr.g4
Explanation: Testing an <span style="font-variant:small-caps;">Antlr</span> Grammar via grun
In order for the examples using <span style="font-variant:small-caps;">Antlr</span> to work,
we first have to install <span style="font-variant:small-caps;">Antlr</span>. This can ... |
14,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Newton's method
Step1: Cf. "Why Functional Programming Matters" by John Hughes
$a_{i+1} = \frac{(a_i+\frac{n}{a_i})}{2}$
Let's define a function that computes the above equation
Step2: And... | Python Code:
from notebook_preamble import J, V, define
Explanation: Newton's method
End of explanation
define('Q == [tuck / + 2 /] unary')
Explanation: Cf. "Why Functional Programming Matters" by John Hughes
$a_{i+1} = \frac{(a_i+\frac{n}{a_i})}{2}$
Let's define a function that computes the above equation:
n a Q
... |
14,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3T_Pandas Basic (3) - 데이터 그룹화 ( df.groupby )
Group by라는 기능. 그룹을 나눈다는 의미
df에서 관계있는 애들만 뽑아내는 작업
번외로 중복되지 않은 값들을 뽑아내는 것까지
Step1: 중복되지 않는 “시”의 리스트
Step2: 각각의 df으로 만들고 싶다. (서울df, 부산df, 경북df)
fo... | Python Code:
df = pd.DataFrame(columns=["시", "동"])
df
df.loc[0] = ["서울", "신사동"]
df.loc[1] = ["서울", "대치동"]
df.loc[2] = ["서울", "봉천동"]
df.loc[3] = ["부산", "부산 1동"]
df.loc[4] = ["부산", "부산 2동"]
df.loc[5] = ["경북", "효자동"]
df.loc[6] = ["경북", "지곡동"]
df
Explanation: 3T_Pandas Basic (3) - 데이터 그룹화 ( df.groupby )
Group by라는 기능. 그룹을 ... |
14,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 17
Step1: A list of Dictionaries isa Data Structure.
Step2: The Tic-Tac-Toe Game Program
We can use data structures to represent values in Python that can be understood. For example... | Python Code:
cat = {'name' : 'Zophie', 'age': 7, 'color':'gray'}
Explanation: Lesson 17:
Data Structures
Lists and dictionaries organize data in structures for programs.
End of explanation
allCats = []
allCats.append({'name' : 'Zophie', 'age': 7, 'color':'gray'})
allCats.append({'name' : 'Fooka', 'age': 5, 'color':'bla... |
14,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Math - Linear Algebra
Linear Algebra is the branch of mathematics that studies vector spaces and linear transformations between vector spaces, such as rotating a shape, scaling it up or down... | Python Code:
from __future__ import division, print_function, unicode_literals
Explanation: Math - Linear Algebra
Linear Algebra is the branch of mathematics that studies vector spaces and linear transformations between vector spaces, such as rotating a shape, scaling it up or down, translating it (ie. moving it), etc.... |
14,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Closures
Before getting into closures lets understand nested functions. A function defined inside another function is called a nested function. Nested functions can access variables of the e... | Python Code:
def print_msg(msg): # This is the outer enclosing function
def printer(): # This is the nested function
print(msg)
printer()
print_msg('Hello')
Explanation: Closures
Before getting into closures lets understand nested functions. A function defined inside another function is calle... |
14,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Toy weather data
Here is an example of how to easily manipulate a toy weather dataset using xarray and other recommended Python libraries
Step1: Examine a dataset with pandas and seaborn
St... | Python Code:
import xarray as xr
import numpy as np
import pandas as pd
import seaborn as sns # pandas aware plotting library
np.random.seed(123)
times = pd.date_range('2000-01-01', '2001-12-31', name='time')
annual_cycle = np.sin(2 * np.pi * (times.dayofyear / 365.25 - 0.28))
base = 10 + 15 * annual_cycle.reshape(-1, ... |
14,894 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing the NFFT
Step2: We want to solve the following
Step3: Let's try evaluating this on some sinusoidal data, with a frequency of 10 cycles per unit time
Step4: As expected, the N... | Python Code:
from __future__ import division
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Implementing the NFFT
End of explanation
def ndft(x, f, N):
non-equispaced discrete Fourier transform
k = -(N // 2) + np.arange(N)
return np.dot(f, np.exp(2j * np.pi * k * x[:, np.... |
14,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'thu', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: THU
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics: Transport, Emiss... |
14,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
STELLAB test notebook
The STELLAB module (which is a contraction for Stellar Abundances) enables to plot observational data for comparison with galactic chemical evolution (GCE) predictions.... | Python Code:
# Import the needed packages
import matplotlib
import matplotlib.pyplot as plt
# Import the observational data module
import stellab
import sys
# Trigger interactive or non-interactive depending on command line argument
__RUNIPY__ = sys.argv[0]
if __RUNIPY__:
%matplotlib inline
else:
%pylab nbagg
E... |
14,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python
Step1: This plot shows the simulated data as black points with error bars and the true function is shown as a gray line.
Now let's build the celerite model that we'll use to fit the ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
t = np.sort(np.append(
np.random.uniform(0, 3.8, 57),
np.random.uniform(5.5, 10, 68),
)) # The input coordinates must be sorted
yerr = np.random.uniform(0.08, 0.22, len(t))
y = 0.2 * (t-5) + np.sin(3*t + 0.1*(t-5)**2) + yerr * n... |
14,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OWSLib versus Birdy
This notebook shows a side-by-side comparison of owslib.wps.WebProcessingService and birdy.WPSClient.
Step1: Displaying available processes
With owslib, wps.processes is... | Python Code:
from owslib.wps import WebProcessingService
from birdy import WPSClient
url = "https://bovec.dkrz.de/ows/proxy/emu?Service=WPS&Request=GetCapabilities&Version=1.0.0"
wps = WebProcessingService(url)
cli = WPSClient(url=url)
Explanation: OWSLib versus Birdy
This notebook shows a side-by-side comparison of ow... |
14,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
On this page you'll find a series of exercises. We'll be using Python for all the code, but not really. You barely need to know any Python at all. In fact here is all you need to know (at... | Python Code:
from basic_functions import *
is_empty([1,2])
is_empty([])
head([1,2])
head([1])
Explanation: On this page you'll find a series of exercises. We'll be using Python for all the code, but not really. You barely need to know any Python at all. In fact here is all you need to know (at least about Python).
A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.