Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
13,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Point Particles
Step1: While this would work for defining a single molecule or very small system, this would not be efficient for large systems. Instead, the clone and translate operator c... | Python Code:
import mbuild as mb
class MonoLJ(mb.Compound):
def __init__(self):
super(MonoLJ, self).__init__()
lj_particle1 = mb.Particle(name='LJ', pos=[0, 0, 0])
self.add(lj_particle1)
lj_particle2 = mb.Particle(name='LJ', pos=[1, 0, 0])
self.add(lj_particle2)
lj_pa... |
13,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_io_export_pandas
Step1: Export DataFrame
Step2: Explore Pandas MultiIndex | Python Code:
# Author: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
import matplotlib.pyplot as plt
import numpy as np
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = dat... |
13,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Laboratoire d'introduction au filtrage
Cours NSC-2006, année 2015
Méthodes quantitatives en neurosciences
Pierre Bellec, Yassine Ben Haj Ali
Objectifs
Step1: Section 1
Step2: Représentez ... | Python Code:
%matplotlib inline
from pymatbridge import Octave
octave = Octave()
octave.start()
%load_ext pymatbridge
Explanation: Laboratoire d'introduction au filtrage
Cours NSC-2006, année 2015
Méthodes quantitatives en neurosciences
Pierre Bellec, Yassine Ben Haj Ali
Objectifs:
Ce laboratoire a pour but de vous in... |
13,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates ... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.viz import plot_topomap
import mne
from mne.stats imp... |
13,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word Frequencies
Can we identify different types of text documents based on the frequency of their words? Can we identify different authors, styles, or disciplines like medical versus inform... | Python Code:
from urllib.request import urlopen
# from urllib.request import *
# in order to get the help text, we should import the whole subpackage.
import urllib.request
help(urllib.request)
help(urlopen)
Explanation: Word Frequencies
Can we identify different types of text documents based on the frequency of their ... |
13,905 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Decision Tree Regressor - Training a Decision Tree Regression Model
| Python Code::
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error
# initialise & fit Decision Tree Regressor
model = DecisionTreeRegressor(criterion='squared_error',
... |
13,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Principal Component Analysis
by Rene Zhang and Max Margenot
Part of the Quantopian Lecture Series
Step1: We will introduce PCA with an image processing example. A grayscale digital image ca... | Python Code:
from numpy import linalg as LA
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Principal Component Analysis
by Rene Zhang and Max Margenot
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
https://github.com/quantopian/research_public
Applications in man... |
13,907 | 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', 'miroc', 'miroc-es2h', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: MIROC
Source ID: MIROC-ES2H
Topic: Atmos
Sub-Topics: Dynamical Core, Radiat... |
13,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1"><a href="#Data-Wrangling-with-Pandas"><span class="toc-item-num">1 </span>Data Wrangling with Pandas</a></div><div class="lev2"><a href="#Da... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('notebook')
Explanation: Table of Contents
<p><div class="lev1"><a href="#Data-Wrangling-with-Pandas"><span class="toc-item-num">1 </span>Data Wrangling with Pandas</a>... |
13,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook demonstrates how to leverage transfer learning to use your own image dataset to build and train an image classification model using MXNet and Amazon SageMaker.
We use, as an ex... | Python Code:
import os
import urllib.request
import boto3, botocore
import sagemaker
from sagemaker import get_execution_role
import mxnet as mx
mxnet_path = mx.__file__[ : mx.__file__.rfind('/')]
print(mxnet_path)
role = get_execution_role()
print(role)
sess = sagemaker.Session()
Explanation: This notebook demonstrate... |
13,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
```
Read data
with open("Atmosfera-Incidents-2017.pickle", 'rb') as f
Step1: W tej wersji eksperymentu, Y zawiera root_service - 44 unikalne kategorie główne.
Zamieńmy je na liczby z przed... | Python Code:
# Dane wejściowe
with open("X-sequences.pickle", 'rb') as f:
X = pickle.load(f)
with open("Y.pickle", 'rb') as f:
Y = pickle.load(f)
# Zostaw tylko poniższe kategorie, pozostale zmień na -1
lista = [2183,
#325,
37, 859, 2655, 606, 412, 2729, 1683, 1305]
# Y=[y if y in lista... |
13,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Models Exercise 2
Imports
Step1: Fitting a decaying oscillation
For this problem you are given a raw dataset in the file decay_osc.npz. This file contains three arrays
Step2: Now, ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 2
Imports
End of explanation
# YOUR CODE HERE
data = np.load("decay_osc.npz")
t = data["tdata"]
y = data["ydata"]
dy = data["dy"]
plt.errorbar(t, y, dy, fmt=".b")
assert T... |
13,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CBOE VXXLE Index
In this notebook, we'll take a look at the CBOE VXXLE Index dataset, available on the Quantopian Store. This dataset spans 16 Mar 2011 through the current day. This data ha... | Python Code:
# For use in Quantopian Research, exploring interactively
from quantopian.interactive.data.quandl import cboe_vxxle as dataset
# import data operations
from odo import odo
# import other libraries we will use
import pandas as pd
# Let's use blaze to understand the data a bit using Blaze dshape()
dataset.ds... |
13,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mathematical functions
Step1: Trigonometric functions
Q1. Calculate sine, cosine, and tangent of x, element-wise.
Step2: Q2. Calculate inverse sine, inverse cosine, and inverse tangent of ... | Python Code:
import numpy as np
np.__version__
__author__ = "kyubyong. kbpark.linguist@gmail.com. https://github.com/kyubyong"
Explanation: Mathematical functions
End of explanation
x = np.array([0., 1., 30, 90])
print "sine:", np.sin(x)
print "cosine:", np.cos(x)
print "tangent:", np.tan(x)
Explanation: Trigonometric ... |
13,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q2
More on writing functions!
A
Write a function, flexible_mean, which computes the average of any number of numbers.
takes a variable number of floating-point arguments
returns 1 number
Ste... | Python Code:
import numpy as np
np.testing.assert_allclose(1.5, flexible_mean(1.0, 2.0))
np.testing.assert_allclose(0.0, flexible_mean(-100, 100))
np.testing.assert_allclose(1303.359375, flexible_mean(1, 5452, 43, 34, 40.23, 605.2, 4239.2, 12.245))
Explanation: Q2
More on writing functions!
A
Write a function, flexible... |
13,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Periodic Signals & The Lomb-Scargle Periodogram
Version 0.1
By AA Miller (CIERA/Northwestern & Adler)
This notebook discusses the detection of periodic signals in noisy, irregular data (the ... | Python Code:
def gen_periodic_data(x, period=1, amplitude=1, phase=0, noise=0):
'''Generate periodic data given the function inputs
y = A*cos(x/p - phase) + noise
Parameters
----------
x : array-like
input values to evaluate the array
period : float (default=1)
per... |
13,916 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I try to retrieve percentiles from an array with NoData values. In my case the Nodata values are represented by -3.40282347e+38. I thought a masked array would exclude this values (... | Problem:
import numpy as np
DataArray = np.arange(-5.5, 10.5)
percentile = 50
mdata = np.ma.masked_where(DataArray < 0, DataArray)
mdata = np.ma.filled(mdata, np.nan)
prob = np.nanpercentile(mdata, percentile) |
13,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Social Network Analysis
Written by Jin Cheong & Luke Chang
Step1: Primer to Network Analysis
A network is made up of two main components
Step2: Now we can add a node using the .add_node('n... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
try:
import networkx as nx
except:
# Install NetworkX
!pip install networkx
Explanation: Social Network Analysis
Written by Jin Cheong & Luke Chang
End of explanation
# Initialize Graph object
G = nx.Graph()
Explanation: Prim... |
13,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Annotating continuous data
This tutorial describes adding annotations to a ~mne.io.Raw object,
and how annotations are used in later stages of data processing.
Step1: ~mne.Annotations i... | Python Code:
import os
from datetime import timedelta
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.c... |
13,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Classification With Keras Convolutional Neural Network
Step2: Configuration and Hyperparameters
First let's go ahead and define our custom early stopping class, which will be used in ... | Python Code:
from __future__ import print_function, division
import numpy as np
import random
import os
import glob
import cv2
import datetime
import pandas as pd
import time
import h5py
import csv
from scipy.misc import imresize, imsave
from sklearn.cross_validation import KFold, train_test_split
from sklearn.metrics ... |
13,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PanSTARRS - WISE cross-match
Step1: Load the data
Load the catalogues
Step2: Restrict the study to the well sampled area
Step3: Coordinates
As we will use the coordinates to make a cross-... | Python Code:
import numpy as np
from astropy.table import Table
from astropy import units as u
from astropy.coordinates import SkyCoord, search_around_sky
from mltier1 import generate_random_catalogue, Field, Q_0
%load_ext autoreload
%pylab inline
field = Field(170.0, 190.0, 45.5, 56.5)
Explanation: PanSTARRS - WISE cr... |
13,921 | 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', 'messy-consortium', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: SANDBOX-1
Topic: Landice
Sub-Topi... |
13,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Work on getting $E$ vs $\theta$ plot parameters w/ 3 extrema
Step1: Generalized Landau Model of Ferroelectric Liquid Crystals
Step2: $f(c,p) = \dfrac{1}{2}r_{c}c^{2}+\dfrac{1}{4}u_{c}c^{4}... | Python Code:
%matplotlib inline
from sympy import *
import matplotlib.pyplot as plt
import numpy as np
init_printing(use_unicode=True)
r, u, v, c, r_c, u_c, v_c, E, p, r_p, u_p, v_p, e, a, b, q, b_0, b_1, b_2, b_3, q_0, q_1, q_2, q_3, q_4, q_5, beta, rho, epsilon, delta, d, K_3, Omega, Lambda, lamda, C, mu, Gamma, tau,... |
13,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LQ Approximation with QuantEcon.py
Step2: We consider a dynamic maximization problem with
reward function $f(s, x)$,
state transition function $g(s, x)$, and
discount rate $\delta$,
where $... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import quantecon as qe
# matplotlib settings
plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0
Explanation: LQ Approximation with QuantEcon.py
End of explanation
def approx_lq(s_star, x_star, f_star, Df_star, DDf_star, g_star, Dg_star, disc... |
13,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data info
Data notes
Wave I, the main survey, was fielded between February 21 and April 2, 2009. Wave 2 was fielded March 12, 2010 to June 8, 2010. Wave 3 was fielded March 22, 2011 to Augus... | Python Code:
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
pd.options.display.max_columns=1000
Explanation: Data info
Data notes
Wave I, the main survey, was fielded between February 21 and April 2, 2009. Wave 2 was fielded March 12, 2010 to June 8, 2010... |
13,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WNx - 06 June 2017
Practical Deep Learning I Lesson 4 CodeAlong
Lesson4 JNB
Step1: Set up Data
We're working with the movielens data, which contains one rating per row, like this
Step2: Ju... | Python Code:
import theano
import sys, os
sys.path.insert(1, os.path.join('utils'))
%matplotlib inline
import utils; reload(utils)
from utils import *
from __future__ import print_function, division
path = "data/ml-latest-small/"
model_path = path + 'models/'
if not os.path.exists(model_path): os.mkdir(model_path)
batc... |
13,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deploying NVIDIA Triton Inference Server in AI Platform Prediction Custom Container (Google Cloud SDK)
In this notebook, we will walk through the process of deploying NVIDIA's Triton Inferen... | Python Code:
PROJECT_ID='[Enter project name - REQUIRED]'
REPOSITORY='caipcustom'
REGION='us-central1'
TRITON_VERSION='20.06'
import os
import random
import requests
import json
MODEL_BUCKET='gs://{}-{}'.format(PROJECT_ID,random.randint(10000,99999))
ENDPOINT='https://{}-ml.googleapis.com/v1'.format(REGION)
TRITON_IMAG... |
13,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright (c) 2015, 2016
Sebastian Raschka
Li-Yi Wei
https
Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information,... | Python Code:
%load_ext watermark
%watermark -a '' -u -d -v -p numpy,pandas,matplotlib,sklearn
Explanation: Copyright (c) 2015, 2016
Sebastian Raschka
Li-Yi Wei
https://github.com/1iyiwei/pyml
MIT License
Python Machine Learning - Code Examples
Chapter 3 - A Tour of Machine Learning Classifiers
Logistic regression
Binar... |
13,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Astro 300 Python programming style guide
This notebook is a summary of the python programming style we will use in
Astro 300.
Half of your grade, on each assignment,
will be based on ho... | Python Code:
# Good - Full credit
mass_particle = 10.0
velocity_particle = 20.0
kinetic_energy = 0.5 * mass_particle * (velocity_particle ** 2)
print(kinetic_energy)
# Bad - Half credit at best
x = 10.0
y = 20.0
print(0.5*x*y**2)
# Really bad - no credit
print(0.5*10*20**2)
Explanation: The Astro 300 Python programming... |
13,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This details how the requires decorator can be used.
Step1: The function takes an arbitrary number of strings that describe the dependencies introduced by the class or function.
Step2: So,... | Python Code:
from opt import requires
Explanation: This details how the requires decorator can be used.
End of explanation
@requires('pandas')
def test():
import pandas
print('yay pandas version {}'.format(pandas.__version__))
test()
Explanation: The function takes an arbitrary number of strings that describe t... |
13,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing time with pandas
We've touched a little bit on time so far - mostly how tragic it is to parse - but pandas can do some neat things with it once you figure out how it works.
Let's ... | Python Code:
data_df = pd.read_excel("RESSALES-mf.xlsx", sheetname='data')
data_df.head()
categories_df = pd.read_excel("RESSALES-mf.xlsx", sheetname='categories')
data_types_df = pd.read_excel("RESSALES-mf.xlsx", sheetname='data_types')
error_types_df = pd.read_excel("RESSALES-mf.xlsx", sheetname='error_types')
geo_le... |
13,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neural style transfer
Author
Step1: Let's take a look at our base (content) image and our style reference image
Step2: Image preprocessing / deprocessing utilities
Step3: Compute the styl... | Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import vgg19
base_image_path = keras.utils.get_file("paris.jpg", "https://i.imgur.com/F28w3Ac.jpg")
style_reference_image_path = keras.utils.get_file(
"starry_night.jpg", "https://i.imgur.com/9ooB... |
13,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bloques, índices y un primer ejercicio
Hablaremos de la indexación que normalmente se utiliza en los códigos de CUDA C y que además nos ayudará a comprender mejor los bloques.
Sin más, prese... | Python Code:
%%writefile Programas/Mul_vectores.cu
__global__ void multiplicar_vectores(float * device_A, float * device_B, float * device_C, int TAMANIO)
{
// Llena el kernel escribiendo la multiplicacion de los vectores A y B
}
int main( int argc, char * argv[])
{
int TAMANIO 1000 ;
float h_A[TAMANIO] ;
... |
13,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Atoms
Atoms are defined as a list of strings here.
Step1: Generate some random coordinates
Making some random $x,y,z$ coordinates up
Step2: Molecule
Here we've defined a molecule as a dict... | Python Code:
Atoms = ["C", "B", "H"]
Explanation: Atoms
Atoms are defined as a list of strings here.
End of explanation
Coordinates = []
for AtomNumber in range(len(Atoms)):
Coordinates.append(np.random.rand(3))
Explanation: Generate some random coordinates
Making some random $x,y,z$ coordinates up
End of explanati... |
13,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to your assignment! Do the questions and write the answers in the code cells provided below.
Here's a bit of setup for you.
Step1: Question 1
Step2: Question 2
Step3: Question 3
S... | Python Code:
%pylab inline
import numpy as np
Explanation: Welcome to your assignment! Do the questions and write the answers in the code cells provided below.
Here's a bit of setup for you.
End of explanation
a =
# test_shape
assert a.shape == (100, 100), "Shape is wrong :("
Explanation: Question 1: Create a 100 x 100... |
13,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fisher's Iris data set is a collection of measurements commonly used to discuss various example algorithms. It is popular due to the fact that it consists of multiple dimensions, a large eno... | Python Code:
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.decomposition import PCA
import seaborn as sns
import pandas as pd
import numpy as np
# import some data to play with
iris = datasets.load_iris()
dfX = pd.DataFrame(iris.data,columns = ['sepal_length','sepal_width','petal_length... |
13,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial Part 15
Step2: Make The Datasets
Because ScScore is trained on relative complexities we have our X tensor in our dataset has 3 dimensions (sample_id, molecule_id, features). the 1... | Python Code:
%tensorflow_version 1.x
!curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import deepchem_installer
%time deepchem_installer.install(version='2.3.0')
import deepchem as dc
# Lets get some molecules to play with
from deepchem.molnet.load_func... |
13,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
%matplotlib inline
%pylab inline
... |
13,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corpus similarity
The goal of this notebook is to compare the two corpuses -- the final and the homework, to find some sort of difference between the two
Step1: Combined Clustering
Step2: ... | Python Code:
# Necessary imports
import os
import time
from nbminer.notebook_miner import NotebookMiner
from nbminer.cells.cells import Cell
from nbminer.features.features import Features
from nbminer.stats.summary import Summary
from nbminer.stats.multiple_summary import MultipleSummary
from nbminer.encoders.ast_grap... |
13,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model27
Step1: KMeans
Step2: B. Modeling
Step3: Original
=== Bench with ElasticNetCV | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from utils import load_buzz, select, write_result
from features import featurize, get_pos
from containers import Questions, Users, Categories
from nlp import extract_entities
Explanation: Model27: We are at the last chance!
End of explan... |
13,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
13,941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Canonical Correlation Analysis (CCA)
Example is taken from Section 12.5.3, Machine Learning
Step1: Set up shapes, variables and constants
We have two observed variables x and y of shapes (D... | Python Code:
from symgp import *
from sympy import *
from IPython.display import display, Math, Latex
Explanation: Canonical Correlation Analysis (CCA)
Example is taken from Section 12.5.3, Machine Learning: A Probabilistic Perspective by Kevin Murphy.
End of explanation
# Shapes
D_x, D_y, L_o, L_x, L_y = symbols('D_x,... |
13,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http
Step1: Authenticate to Earth Engine
This should be the same account you used to login to Cloud previously... | Python Code:
from google.colab import auth
auth.authenticate_user()
Explanation: <table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/Earth_Engine_TensorFlow_logistic_regression.ipynb">
<img sr... |
13,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Average Reward over time
Step1: Visualizing what the agent is seeing
Starting with the ray pointing all the way right, we have one row per ray in clockwise order.
The numbers for each ray a... | Python Code:
g.plot_reward(smoothing=100)
Explanation: Average Reward over time
End of explanation
g.__class__ = KarpathyGame
np.set_printoptions(formatter={'float': (lambda x: '%.2f' % (x,))})
x = g.observe()
new_shape = (x[:-4].shape[0]//g.eye_observation_size, g.eye_observation_size)
print(x[:-4].reshape(new_shape))... |
13,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Introduction to Testing
Testing is an easy thing to understand but there is also an art to it as well; writing good tests often requires you to try to figure out what input(s) are mos... | Python Code:
def divide(a, b):
"a, b are ints or floats. Returns a/b
return a / b
Explanation: Introduction to Testing
Testing is an easy thing to understand but there is also an art to it as well; writing good tests often requires you to try to figure out what input(s) are most likely to break your program.
I... |
13,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Augmented Reality Markers (ar_markers)
Kevin J. Walchko, created 11 July 2017
We are not going to do augmented reality, but we are going to learn how the markers work and use it for robotics... | Python Code:
%matplotlib inline
from __future__ import print_function
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
import cv2
import time
# make sure you have installed the library with:
# pip install -U ar_markers
from ar_markers import detect_markers
Explanation: Augmente... |
13,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started With Python
Installation
There are various ways to install Python. Assuming the reader is not (yet) well versed in programming, I suggest to download the Anaconda distributio... | Python Code:
from IPython.display import YouTubeVideo
from datetime import timedelta
YouTubeVideo('jZ952vChhuI')
Explanation: Getting Started With Python
Installation
There are various ways to install Python. Assuming the reader is not (yet) well versed in programming, I suggest to download the Anaconda distribution, w... |
13,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #01
Simple Linear Model
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial demonstrates the basic workflow of using TensorFlow with a s... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
Explanation: TensorFlow Tutorial #01
Simple Linear Model
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial demonstrates the basic wo... |
13,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample for KFServing SDK with a custom image
This is a sample for KFServing SDK using a custom image.
The notebook shows how to use KFServing SDK to create, get and delete InferenceService w... | Python Code:
# Set this to be your dockerhub username
# It will be used when building your image and when creating the InferenceService for your image
DOCKER_HUB_USERNAME = "your_docker_username"
%%bash -s "$DOCKER_HUB_USERNAME"
docker build -t $1/kfserving-custom-model ./model-server
%%bash -s "$DOCKER_HUB_USERNAME"
d... |
13,949 | 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
import random
#data_dir = './data/simpsons/moes_tavern_lines.txt'
#data_dir = './data/all/simpsons_all.csv'
data_dir = './data/all/simpsons_norm_names_all.csv'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
te... |
13,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poisson Processes
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: This chapter introduces the Poisson process, which is a model used to describe events that occur ... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
13,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.soft - Notions de SQL - correction
Correction des exercices du premier notebooks relié au SQL.
Step1: Recupérer les données
Step2: Exercice 1
Step3: Exercice 2
Step4: Exercice 3
Step... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
Explanation: 1A.soft - Notions de SQL - correction
Correction des exercices du premier notebooks relié au SQL.
End of explanation
import os
if not os.path.exists("td8_velib.db3"):
from pyensae.datasource import download_... |
13,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MIDAS Examples
If you're reading this you probably already know that MIDAS stands for Mixed Data Sampling, and it is a technique for creating time-series forecast models that allows you to m... | Python Code:
%matplotlib inline
import datetime
import numpy as np
import pandas as pd
from midas.mix import mix_freq
from midas.adl import estimate, forecast, midas_adl, rmse
Explanation: MIDAS Examples
If you're reading this you probably already know that MIDAS stands for Mixed Data Sampling, and it is a technique fo... |
13,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Import the necessary packages to read in the data, plot, and create a linear regression model
Step1: 2. Read in the hanford.csv file
Step2: <img src="images/hanford_variables.png">
3. C... | Python Code:
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line)
import statsmodels.formula.api as smf
Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model
End of explanation
df = pd.... |
13,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Вспомогательные функции
Step4: Тест для метода прогонки
source
Step5: source
Step6: Тесты для создания массивов
Step7: Создание класса модели
Ссылки
Step8: Тесты для 1 задачи | Python Code:
# Плотность источников тепла
def func(s, t):
#return 0.
return s + t * 4.
# Температура внешней среды
def p(t):
return math.cos(2 * t * math.pi)
#return t
def array(f, numval, numdh):
Создать N-мерный массив.
param: f - функция, которая приминает N аргументов.
para... |
13,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This Notebook illustrates the usage of OpenMC's multi-group calculational mode with the Python API. This example notebook creates and executes the 2-D C5G7 benchmark model using the openmc.M... | Python Code:
import os
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import openmc
%matplotlib inline
Explanation: This Notebook illustrates the usage of OpenMC's multi-group calculational mode with the Python API. This example notebook creates and executes the 2-D C5G7 benchmark... |
13,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step3: Moving average
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step4: Trend and Seasonality
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,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 下面读取上一节存储的训练集和测试集回测数据,如下所示:
Step2: 1. A股训练集主裁训练
下面开始使用训练集交易数据训练主裁,裁判组合使用两个abupy中内置裁判AbuUmpM... | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets
%matplotlib inline
import os
import sys
# 使用insert 0即只使用gi... |
13,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Do generations exist?
This notebook contains a "one-day paper", my attempt to pose a research question, answer it, and publish the results in one work day (May 13, 2016).
Copyright 2016 Alle... | Python Code:
from __future__ import print_function, division
from thinkstats2 import Pmf, Cdf
import thinkstats2
import thinkplot
import pandas as pd
import numpy as np
from scipy.stats import entropy
%matplotlib inline
Explanation: Do generations exist?
This notebook contains a "one-day paper", my attempt to pose a re... |
13,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Git
Authors
Step1: Looking at files in a repo
A repository is just a directory. Let's poke around.
Step2: The special .git directory is where git stores all its magic. If you de... | Python Code:
cd /tmp
# Delete the repo if it happens to already exist:
!rm -rf git-intro
# Create the repo
!git clone https://github.com/DS-100/git-intro git-intro
!ls -lh | grep git-intro
cd git-intro
Explanation: Intro to Git
Authors: Henry Milner, Andrew Do. Some of the material in this notebook is inspired by lect... |
13,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Win/Loss Betting Model
Step1: Obtain results of teams within the past year
Step2: Pymc Model
Determining Binary Win Loss
Step3: Save Model
Step4: Diagnostics
Step5: Moar Plots
Step6: N... | Python Code:
import pandas as pd
import numpy as np
import datetime as dt
from scipy.stats import norm, bernoulli
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from spcl_case import *
plt.style.use('fivethirtyeight')
Explanation: Win/Loss Betting Model
End of explanation
h_matches = pd.read_c... |
13,961 | 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', 'messy-consortium', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: SANDBOX-1
Topic: Land
Sub-Topics: Soil,... |
13,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pyplot tutorial
Khi chỉ cung cấp 1 list cho hàm plot() matplotlib sẽ giả sử nó là y values và tự động tạo các giá trị x mặc định (bắt đầu từ 0, có cùng len với y ).
Step1: Nếu được cung cấ... | Python Code:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
Explanation: Pyplot tutorial
Khi chỉ cung cấp 1 list cho hàm plot() matplotlib sẽ giả sử nó là y values và tự động tạo các giá trị x mặc định (bắt đầu từ 0, có cùng len với y ).
End of explanation
import matplotlib.p... |
13,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q 1 (function practice)
Let's practice functions. Here's a simple function that takes a string and returns a list of all the 4 letter words
Step1: Write a version of this function that tak... | Python Code:
def four_letter_words(message):
words = message.split()
four_letters = [w for w in words if len(w) == 4]
return four_letters
message = "The quick brown fox jumps over the lazy dog"
print(four_letter_words(message))
Explanation: Q 1 (function practice)
Let's practice functions. Here's a simple ... |
13,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Experimenting with CV Scores
CVScores displays cross validation scores as a bar chart with the
average of the scores as a horizontal line.
Step2: Classification
Step3: Regression | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import StratifiedKFold
from yellowbrick.model_selection import CVScores
import os
from yellowbrick.download import download_all
## The path to the test data sets
FIXTURES = os.pat... |
13,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
k-Nearest Neighbor (kNN) exercise
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib... |
13,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Introduction and Foundations
Project
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the shi... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the datas... |
13,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explaining quantitative measures of fairness
This hands-on article connects explainable AI methods with fairness measures and shows how modern explainability methods can enhance the usefulne... | Python Code:
# here we define a function that we can call to execute our simulation under
# a variety of different alternative scenarios
import scipy as sp
import numpy as np
import matplotlib.pyplot as pl
import pandas as pd
import shap
%config InlineBackend.figure_format = 'retina'
def run_credit_experiment(N, job_hi... |
13,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GEOL351 Lab 9
Multiple Climate Equilibria
Step1: Outgoing Long-wave radiation
Let us define a function that will compute outgoing longwave emission from the planet for a given emission temp... | Python Code:
%matplotlib inline
# ensures that graphics display in the notebook
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("./CoursewareModules")
from ClimateUtilities import * # import Ray Pierrehumbert's climate utilities
import phys
import seaborn as sns
Expla... |
13,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: データ増強
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: データセットをダウンロードする
このチュートリアルでは、tf_flowers データ... | 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,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The first step in any data analysis is acquiring and munging the data
Our starting data set can be found here
Step1: Problems
Step2: Problems
Step3: Problems
Step4: If we want to look at... | Python Code:
running_id = 0
output = [[0]]
with open("E:/output.txt") as file_open:
for row in file_open.read().split("\n"):
cols = row.split(",")
if cols[0] == output[-1][0]:
output[-1].append(cols[1])
output[-1].append(True)
else:
output.append(cols)
... |
13,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic kaggle competition with SVM
Step1: Let's load and examine the titanic data with pandas first.
Step2: So we have 891 training examples with 10 information columns given. Of course i... | Python Code:
#import all the needed package
import numpy as np
import scipy as sp
import re
import pandas as pd
import sklearn
from sklearn.cross_validation import train_test_split,cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn import metrics
import matplotlib
from matplotlib import pypl... |
13,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extracting SQL code from SSIS dtsx packages with Python lxml
Code for the blog post Extracting SQL code from SSIS dtsx packages with Python lxml
From Analyze the Data not the Drivel
Step1: ... | Python Code:
# imports
import os
from lxml import etree
# set sql output directory
sql_out = r"C:\temp\dtsxsql"
if not os.path.isdir(sql_out):
os.makedirs(sql_out)
# set dtsx package file
ssis_dtsx = r'C:\temp\dtsx\ParseXML.dtsx'
if not os.path.isfile(ssis_dtsx):
print("no package file")
# read and parse ssis p... |
13,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
아나콘다(Anaconda) 소개
수정 사항
파이썬3 이용 아나콘다 팩키지 설치 이미지 업데이트 필요
아나콘다 패키지 소개
파이썬 프로그래밍 언어 개발환경
파이썬 기본 패키지 이외에 데이터분석용 필수 패키지 포함
기본적으로 스파이더 에디터를 활용하여 강의 진행
아나콘다 패키지 다운로드
아나콘다 패키지를 다운로드 하려면 아래 사이트를 방문... | Python Code:
a = 2
b = 3
a + b
Explanation: 아나콘다(Anaconda) 소개
수정 사항
파이썬3 이용 아나콘다 팩키지 설치 이미지 업데이트 필요
아나콘다 패키지 소개
파이썬 프로그래밍 언어 개발환경
파이썬 기본 패키지 이외에 데이터분석용 필수 패키지 포함
기본적으로 스파이더 에디터를 활용하여 강의 진행
아나콘다 패키지 다운로드
아나콘다 패키지를 다운로드 하려면 아래 사이트를 방문한다
https://www.anaconda.com/download/
이후 아래 그림을 참조하여 다운받는다.
주의: 강의에서는 파이썬 3 최신 버전을 사용한... |
13,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Remote DCOM IErtUtil DLL Hijack
Metadata
| | |
|
Step1: Download & Process Mordor Dataset
Step2: Analytic I
Look for non-system accounts SMB accessing a C
Step3: Anal... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Remote DCOM IErtUtil DLL Hijack
Metadata
| | |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2020/10/09 |
| modification date | 2020/10/09 |
| playbook relate... |
13,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluating Classifiers
Goals
Step1: The naive bayes algorithm gets 79.5% accuracy.
Does this seem like a good way to check the accuracy? It shouldn't! We tested our accuracy on the same d... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv('../scikit/tweets.csv')
text = df['tweet_text']
target = df['is_there_an_emotion_directed_at_a_brand_or_product']
# Remove the blank rows:
fixed_target = target[pd.notnull(text)]
fixed_text = text[pd.notnull(text)]
# Perform feature extraction:
from s... |
13,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Import the necessary packages to read in the data, plot, and create a linear regression model
Step1: 2. Read in the hanford.csv file
Step2: <img src="images/hanford_variables.png">
3. C... | Python Code:
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line)
import statsmodels.formula.api as smf
Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model
End of explanation
cd C:\Us... |
13,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Migrate metrics and optimizers
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: and prepare ... | 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,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Why vectorisation
Vectorisation examples
Scalar class - recap
Class with vectorised weights
Class with vectorised weights and inputs
Exercise
Setup
Step1: Testing vectorisation
Ste... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, mean_squared_error, log_loss
from tqdm import tqdm_notebook
import seaborn as sns
import imageio
import time
from... |
13,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using LAMMPS with iPython and Jupyter
LAMMPS can be run interactively using iPython easily. This tutorial shows how to set this up.
Installation
Download the latest version of LAMMPS into a ... | Python Code:
from lammps import IPyLammps
L = IPyLammps()
# 2d circle of particles inside a box with LJ walls
import math
b = 0
x = 50
y = 20
d = 20
# careful not to slam into wall too hard
v = 0.3
w = 0.08
L.units("lj")
L.dimension(2)
L.atom_style("bond")
L.boundary("f f p")
L.lattice("hex", 0.85)
L.r... |
13,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Relational database
A lot of data can be stored in tabels
Table Human
|ID|Name| Age |
|--|----|-----|
|1|Anton|34|
|2|Morten|37|
Table Course
|ID|Subject| Hours |
|--|----|-----|
|1|Python|3... | Python Code:
# models.py
from django.db import models
class Human(models.Model):
''' Description of any Human'''
name = models.CharField(max_length=200)
age = models.IntegerField()
objects = models.Manager()
def __str__(self):
''' Nicely print Human object '''
return u"I'm %s, %d ye... |
13,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple DNN model built in Keras.
In this notebook, we will use the ML datasets we read in with our Keras pipeline earlier and build our Keras DNN to predict the fare amount for NYC taxi ca... | Python Code:
%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
import os, json, math
import numpy as np
import shutil
import tensorflow as tf
print("TensorFlow version: ",tf.version.VERSION)
PROJECT = "your-gcp-project-here" # REPLACE WI... |
13,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scrivere su file
Step1: Unicode in breve
mettete sempre la u prima delle stringhe (u"")
v. unicode HowTO nelle references sotto
Step2: Leggere e scrivere files con contenuti Unicode
Step3:... | Python Code:
with open(fname, "wb") as f:
f.write(data)
with open(fname, "rb") as f:
rows = f.readlines(data)
Explanation: Scrivere su file
End of explanation
u"Papa" + u"aè"
Explanation: Unicode in breve
mettete sempre la u prima delle stringhe (u"")
v. unicode HowTO nelle references sotto
End of explana... |
13,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 09b
Step1: In this lab, we're going to cluster documents by the similarity of their text content. For this, we'll need to download some documents to cluster. The following dictionary ma... | Python Code:
%matplotlib inline
import pandas as pd
import urllib2
from sklearn.cluster import AgglomerativeClustering
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
Explanation: Lab 09b: Agglomerative clusteri... |
13,984 | 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
# Show Plot in The Notebook
matplotlib.use("nbagg")
import matplotlib.pyplot as plt
from gll import gll
from lagrange1st import lagrange1st
from... |
13,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Response Files With The Sherpa API
We're going to see if we can get the Sherpa API to allow us to apply ARFs and RMFs to arbitrary models.
Note
Step1: Playing with the Convenience Functions... | Python Code:
%matplotlib notebook
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
Explanation: Response Files With The Sherpa API
We're going to see if we can get the Sherpa API to allow us to apply ARFs and RMFs to arbitrary models.
Note: I needed to run heainit (the heasoft initialization fil... |
13,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
Clustering
Step1: Introducing K-Means
K Means is an algorithm for unsupervised... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
Clustering: K-Means In-Depth
Here we'll explore K Means Clusteri... |
13,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Tile" data-toc-modified-id="Tile-1"><span class="toc-item-num">1 </span>Tile</a></div><div class="lev2 toc-item"><a href=... | Python Code:
import numpy as np
a = np.array([0, 1, 2])
print('a = \n', a)
print()
print('Resultado da operação np.tile(a,2): \n',np.tile(a,2))
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Tile" data-toc-modified-id="Tile-1"><span class="toc-item-num">1 </span>Tile</a></div><div cla... |
13,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute DICS beamfomer on evoked data
Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ beamformer from
single-trial activity in a time-frequency window to estimate source time
cours... | Python Code:
# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)
import mne
import matplotlib.pyplot as plt
import numpy as np
from mne.datasets import sample
from mne.time_frequency import csd_epochs
from mne.beamformer import dics
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path +... |
13,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handling Select2 Controls in Selenium WebDriver
Select2 is a jQuery based replacement for select boxes. This article will demonstrate how Selenium webdriver can handle Select2 by manipulatin... | Python Code:
import os
from marigoso import Test
request = {
'firefox': {
'capabilities': {
'marionette': False,
},
}
}
Explanation: Handling Select2 Controls in Selenium WebDriver
Select2 is a jQuery based replacement for select boxes. This article will demonstrate how Selenium webd... |
13,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-am4', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-AM4
Topic: Aerosol
Sub-Topics: Transport, E... |
13,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table>
<tr>
<td style="text-align
Step1: Graph Execution
TensorFlow executes your code inside a C++ program and returns the results through the TensorFlow API. Since we are usi... | Python Code:
import tensorflow as tf
import sys
print("Python Version:",sys.version.split(" ")[0])
print("TensorFlow Version:",tf.VERSION)
Explanation: <table>
<tr>
<td style="text-align:left;"><div style="font-family: monospace; font-size: 2em; display: inline-block; width:60%">2. Tensors</div><img src="im... |
13,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting sentiment from product reviews
<hr>
Import GraphLab Create
Step1: Read some product review data
Loading reviews for a set of baby products.
Step2: Exploring the data
Data includ... | Python Code:
import graphlab
Explanation: Predicting sentiment from product reviews
<hr>
Import GraphLab Create
End of explanation
products = graphlab.SFrame('amazon_baby.gl/')
Explanation: Read some product review data
Loading reviews for a set of baby products.
End of explanation
products.head()
Explanation: Explorin... |
13,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chopsticks!
A few researchers set out to determine the optimal length of chopsticks for children and adults. They came up with a measure of how effective a pair of chopsticks performed, call... | Python Code:
import pandas as pd
# pandas is a software library for data manipulation and analysis
# We commonly use shorter nicknames for certain packages. Pandas is often abbreviated to pd.
# hit shift + enter to run this cell or block of code
path = r'/Users/pradau/Dropbox/temp/Downloads/chopstick-effectiveness.csv'... |
13,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applying PyMC3 to Marketing Conversion data
One good use of Probabilistic Programming is trying to say something about our conversions.
We'll generate some fake data and do a simple 'transac... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('bmh')
colors = ['#348ABD', '#A60628', '#7A68A6', '#467821', '#D55E00',
'#CC79A7', '#56B4E9', '#009E73', '#F0E442', '#0072B2']
Explanation: Applying PyMC3 to Marketing Conversion data
One good use of Probabilistic Programming is tr... |
13,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
End to End Machine Learning Pipeline for Income Prediction
We use demographic features from the 1996 US census to build an end to end machine learning pipeline. The pipeline is also annotate... | Python Code:
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from... |
13,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Active Directory Replication User Backdoor
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Look for any user accessing directory ser... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Active Directory Replication User Backdoor
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/01/01 |
| modification date | 2020/09/20 |
|... |
13,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a ConvNet PyTorch
In this notebook, you'll learn how to use the powerful PyTorch framework to specify a conv net architecture and train it on the CIFAR-10 dataset.
Step2: What's th... | Python Code:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.utils.data import sampler
import torchvision.datasets as dset
import torchvision.transforms as T
import numpy as np
import timeit
Explanation: Training a Con... |
13,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous Control
In this notebook you will solve continuous control environment using either Twin Delayed DDPG (TD3) or Soft Actor-Critic (SAC). Both are off-policy algorithms that are cur... | Python Code:
!git clone https://github.com/benelot/pybullet-gym lib/pybullet-gym
!pip install -e lib/pybullet-gym
import gym
import numpy as np
import pybulletgym
Explanation: Continuous Control
In this notebook you will solve continuous control environment using either Twin Delayed DDPG (TD3) or Soft Actor-Critic (SAC... |
13,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Step1: In this chapter, we are going to take a look at how to perform statistical inference on graphs.
Statistics refresher
Before we can proceed with statistical inference on ... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo(id="P-0CJpO3spg", width="100%")
Explanation: Introduction
End of explanation
import networkx as nx
G_er = nx.erdos_renyi_graph(n=30, p=0.2)
nx.draw(G_er)
Explanation: In this chapter, we are going to take a look at how to perform statistical inference o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.