Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,700
Given the following text description, write Python code to implement the functionality described below step by step Description: EECS 445 Step1: Let's try several polynomial fits to the data Step2: Let's plot the data with the estimators!
Python Code: import numpy as np import matplotlib.pyplot as plt from numpy.matlib import repmat from sklearn degrees = [1,2,3,4,5] #define data n = 20 sub = 1000 mean = 0 std = 0.25 #define test set Xtest = np.random.random((n,1))*2*np.pi ytest = np.sin(Xtest) + np.random.normal(mean,std,(n,1)) #pre-allocate variables ...
4,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a RNN model to text generation RNN model at character level Input Step1: Download data and generate sequences Download quijote from guttenberg project wget http Step2: Train the mod...
Python Code: # Header from __future__ import print_function import numpy as np import tensorflow as tf print('Tensorflow version: ', tf.__version__) import time #Show images import matplotlib.pyplot as plt %matplotlib inline # plt configuration plt.rcParams['figure.figsize'] = (10, 10) # size of images plt.rcPar...
4,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualisation of the electrostatic field around a charged circular plate This notebook shows how to numerically calculate and visualise the fields around a circular homogeneously charged ins...
Python Code: import numpy as np import matplotlib.pyplot as plt Explanation: Visualisation of the electrostatic field around a charged circular plate This notebook shows how to numerically calculate and visualise the fields around a circular homogeneously charged insulating plate. (C) Jo Verbeeck, EMAT, University of A...
4,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 17 Step1: In addition to the simulation parameters, we start with an initial seed of concentration data. Unlike our other analytical strategies there are no coefficients to compute,...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Lecture 17: Numerical Solutions to the Diffusion Equation (Explicit Methods) Reading and Reference Numerical Recipes, W. Press, Cambridge University Press, 1986 Numerical Methods, R. Hornbeck, Quantum Publishers, 1975 B. Gu...
4,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing McLennan-Tourky in Python Daisuke Oyama Faculty of Economics, University of Tokyo Step1: Univariate example Step2: Let us try the logistic function which is well known to gene...
Python Code: %matplotlib inline import time import numpy as np import matplotlib.pyplot as plt import quantecon as qe from quantecon.compute_fp import _print_after_skip from quantecon.game_theory import Player, NormalFormGame, lemke_howson def compute_fixed_point_ig(f, x_init, error_tol=1e-3, max_iter=50, verbose=1, ...
4,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of Interactive Plotting The IPython notebook excels at interactive science. By its very nature you can easily create a bit of code, run it, look at the output, and adjust the code. T...
Python Code: # Import Module import numpy as np import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt %matplotlib inline import pandas as pd Explanation: Example of Interactive Plotting The IPython notebook excels at interactive science. By its very nature you can easily create a bit of code, r...
4,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Yellowbrick Examples Ths notebook is a sample of the examples that yellowbrick provides. Step1: Load Medical Appointment Data The data used in this example is hosted by Kaggle at following ...
Python Code: import os import sys # Modify the path sys.path.append("..") import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt Explanation: Yellowbrick Examples Ths notebook is a sample of the examples that yellowbrick provides. End of explanation data = pd.read_csv("data/No-show-Issue-Comma...
4,707
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 1 Imports Step2: Trapezoidal rule The trapezoidal rule generates a numerical approximation to the 1d integral Step3: Now use scipy.integrate.quad to integrate the f an...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import integrate Explanation: Integration Exercise 1 Imports End of explanation def trapz(f, a, b, N): Integrate the function f(x) over the range [a,b] with N points. h = (b-a)/N k = np.arange(1,N) I = h * (0.5...
4,708
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', 'miroc', 'nicam16-9d-l78', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-9D-L78 Topic: Aerosol Sub-Topics: Transpor...
4,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 02 Step1: Create a boolean vector called spikes of the same dimensions as before Step2: Restored the variable data from disk, serve warm, and enjoy Step3: Show's over, goodnight
Python Code: import tensorflow as tf sess = tf.InteractiveSession() Explanation: Ch 02: Concept 07 Loading variables Concept 06 was about saving variables. This one's about loading what you saved. Start by creating an interactive session: End of explanation spikes = tf.Variable([False]*8, name='spikes') Explanation: Cr...
4,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Random Forest with Grid Search (XGBoost) <a href="https Step1: This example features Step2: Imports Step3: Log Workflow Prepare Data Step4: Prepare Hyperparameters Step5: Instantiate Cl...
Python Code: # restart your notebook if prompted on Colab try: import verta except ImportError: !pip install verta Explanation: Random Forest with Grid Search (XGBoost) <a href="https://colab.research.google.com/github/VertaAI/modeldb/blob/master/client/workflows/examples/xgboost.ipynb" target="_parent"><img sr...
4,711
Given the following text description, write Python code to implement the functionality described below step by step Description: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Lean Tutorial This tutorial runs through all of the steps for doing a project with Marvin from start-to-finis...
Python Code: from marvin.tools.query import doQuery q, r = doQuery(search_filter='nsa.sersic_logmass >= 10 and nsa.sersic_logmass <= 11', limit=3) Explanation: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Lean Tutorial This tutorial runs through all of the steps for doing a project w...
4,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Suponha que não soubéssemos quantas espécies diferentes estão presentes no dataset iris. Como poderíamos descobrir essa informação aproximadamente a partir dos dados presentes ali? Uma soluç...
Python Code: import pandas as pd iris = # Carregue o arquivo 'datasets/iris_without_classes.csv' # Exiba as primeiras cinco linhas usando o método head() para checar que não existe mais a coluna "Class" Explanation: Suponha que não soubéssemos quantas espécies diferentes estão presentes no dataset iris. Como poderíamo...
4,713
Given the following text description, write Python code to implement the functionality described below step by step Description: <figure> <IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right"> </figure> IHE Python course, 2017 Reading, writing and working with shape files T.N.Olsthoorn 2017-03-15 When working with ...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import shapefile as shp from pprint import pprint Explanation: <figure> <IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right"> </figure> IHE Python course, 2017 Reading, writing and working with shape files T.N.Olsthoorn 2017-03-15 When workin...
4,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Step1: 2. Use mechanize to get reviews for all of the top attractions Step2: Get reviews for top attractions in multiple cities Step3: Finding forms with mechanize
Python Code: # url = 'https://www.tripadvisor.com/Attraction_Review-g60878-d3184389-Reviews-Chihuly_Garden_and_Glass-Seattle_Washington.html#REVIEWS' def get_reviews(response): # response = requests.get(url) soup = BeautifulSoup(response, 'html.parser') entries = soup.findAll('div', {'class': 'entry'}) ...
4,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Mapping fractions between gradient communities in order to perform procrustes Step1: Calculating centroid of binned fraction samples centroid of all 20 replicates for fraction samples that ...
Python Code: %%R otu.tbl.file1 = '/home/nick/notebook/SIPSim/dev/bac_genome1210/atomIncorp_taxaIncorp/0/10/1/OTU_n2_abs1e9_sub-norm_filt.physeq' otu.tbl.file2 = '/home/nick/notebook/SIPSim/dev/bac_genome1210/atomIncorp_taxaIncorp/100/10/1/OTU_n2_abs1e9_sub-norm_filt.physeq' physeq1 = readRDS(otu.tbl.file1) physeq2 = re...
4,716
Given the following text description, write Python code to implement the functionality described below step by step Description: A simple SEA model of two beams Step1: Creating a SEA model To create a SEA model we begin by creating an instance of Model. Step2: We are only interested in a limited frequency range. An ...
Python Code: import sys import seapy import numpy as np %matplotlib inline Explanation: A simple SEA model of two beams End of explanation from acoustics.signal import OctaveBand frequency = OctaveBand(fstart=500.0, fstop=8000.0, fraction=1) system1 = seapy.system.System(frequency) Explanation: Creating a SEA model To ...
4,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 2 assignment This assignment will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game...
Python Code: import random import numpy Explanation: Lab 2 assignment This assignment will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game, which will store information about their current pot, as well as a series o...
4,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing and querying AI Platform Prediction request-response logs in BigQuery This tutorial shows you how to create a view to parse raw request instances and response predictions logged from...
Python Code: !pip install -U -q google-api-python-client !pip install -U -q pandas Explanation: Parsing and querying AI Platform Prediction request-response logs in BigQuery This tutorial shows you how to create a view to parse raw request instances and response predictions logged from AI Platform Prediction to BigQuer...
4,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Small scale example Step1: Example with more savings, but slower to optimize Step2: Look at the recommendations
Python Code: def func(a, b, c): res = tf.einsum('ijk,ja,kb->iab', a, b, c) + 1 res = tf.einsum('iab,kb->iak', res, c) return res a = tf.random_normal((10, 11, 12)) b = tf.random_normal((11, 13)) c = tf.random_normal((12, 14)) # res = func(a, b, c) orders, optimized_func = tf_einsum_opt.optimizer(func, sess,...
4,720
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Energy and RMSE The energy (Wikipedia of a signal corresponds to the total magntiude of the signal. For audio signals, that roughly corresponds to how loud the signal is...
Python Code: x, sr = librosa.load('audio/simple_loop.wav') sr x.shape librosa.get_duration(x, sr) Explanation: &larr; Back to Index Energy and RMSE The energy (Wikipedia of a signal corresponds to the total magntiude of the signal. For audio signals, that roughly corresponds to how loud the signal is. The energy in a s...
4,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Meta-analysis of incubation time for Covid-19 with pediatric subset A wide variety of estimates of the incubation time have been seen in the rapidly evolving Covid-19 literature. As of March...
Python Code: import numpy as np import pandas as pd import os import re import seaborn as sns from datetime import datetime as dt from support_funs_incubation import stopifnot, uwords, idx_find, find_beside, ljoin, sentence_find, record_vals !pip install ansicolors # Takes a tuple (list(idx), sentence) and will print i...
4,722
Given the following text description, write Python code to implement the functionality described below step by step Description: 5 次元削減でデータを圧縮する 特徴部分空間(feature extraction)を作成する 主成分分析(PCA Step1: 5.1.2 特徴変換 Step2: 5.1.3 scikit-learn の主成分分析 Step3: 5.2 線形判別分析による教師ありデータ圧縮 d次元のデータセットを標準化する(dは特徴量の個数) クラスごとにd次元の平均ベクトルを計算する...
Python Code: from IPython.core.display import display from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version import pandas as pd # http://archive.ics.uci.edu/ml/datasets/Wine df_wine = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'...
4,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch4 Writing Structured Programs Assignments Step1: 注意 Step2: Equality 用==是比較兩個元素值是否相同。 用is是比較兩個元素是否參考同一個物件。 Step3: Conditions 將list放在if中,會直接判斷list是否為空,相當於if len(list) &gt; 0 Step4: any()...
Python Code: a = list('hello') # a指向一個list物件 b = a # b指向a所指向的list物件 b[3] = 'x' # 改變物件第3個元素,因為實際件只有一個,所以a,b看到的物件會同時改變 a, b a = ['maybe'] b = [a, a, a] b a[0] = 'will' b Explanation: Ch4 Writing Structured Programs Assignments End of explanation a = ['play'] b = a[:] a[0] = 'zero' a, b a = ['play'] ...
4,724
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in...
Python Code: import jax.numpy as jnp from jax import grad, jit, vmap from jax import random Explanation: Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Lice...
4,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 2 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Split data into training and testi...
Python Code: import graphlab Explanation: Regression Week 2: Multiple Regression (Interpretation) The goal of this first notebook is to explore multiple regression and feature engineering with existing graphlab functions. In this notebook you will use data on house sales in King County to predict prices using multiple ...
4,726
Given the following text description, write Python code to implement the functionality described below step by step Description: We generate some random variates from a non-normal distribution and make a probability plot for it, to show it is non-normal in the tails Step1: We now use boxcox to transform the data so i...
Python Code: # Generate data x = stats.loggamma.rvs(5, size=500) + 5 # Plot it fig = plt.figure(figsize=(6,9)) ax1 = fig.add_subplot(211) prob = stats.probplot(x, dist=stats.norm, plot=ax1) ax1.set_title('Probplot against normal distribution') # Plot an histogram ax2 = fig.add_subplot(212) ax2.hist(x) ax2.set_title('Hi...
4,727
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
4,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: TensorFlowアドオンのコールバック:TimeStopping <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: データのインポートと正規化...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
4,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Preprocess Step2: i2t Step3: t2i
Python Code: import pandas as pd import tensorflow as tf # i2t: image-to-text. i2t_path = '/bigstore/mmt/raw_data/fashion_gen/fashion_gen_i2t_test_pairs.csv' # t2i: text-to-image. t2i_path = '/bigstore/mmt/raw_data/fashion_gen/fashion_gen_t2i_test_pairs.csv' t2i_output_path = '/bigstore/mmt/fashion_gen/metadata/fashion...
4,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Kets are column vectors, i.e. with shape (d, 1) Step1: The normalized=True option can be used to ensure a normalized output. Bras are row vectors, i.e. with shape (1, d) Step2: And operato...
Python Code: qu(data, qtype='ket') Explanation: Kets are column vectors, i.e. with shape (d, 1): End of explanation qu(data, qtype='bra') # also conjugates the data Explanation: The normalized=True option can be used to ensure a normalized output. Bras are row vectors, i.e. with shape (1, d): End of explanation qu(dat...
4,731
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: CMCC Source ID: SANDBOX-3 Sub-Topics: Radiative Forcings. Properties: ...
4,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a song recommender Fire up GraphLab Create Step1: Load music data Step2: Explore data Music data shows how many times a user listened to a song, as well as the details of the song...
Python Code: import graphlab Explanation: Building a song recommender Fire up GraphLab Create End of explanation song_data = graphlab.SFrame('song_data.gl/') Explanation: Load music data End of explanation song_data.head() Explanation: Explore data Music data shows how many times a user listened to a song, as well as t...
4,733
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.e - Enoncé 22 octobre 2019 (2) Correction du second énoncé de l'examen du 22 octobre 2019. L'énoncé propose une façon de disposer des tables carrées dans une salle carrée. Step1: On sait...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.e - Enoncé 22 octobre 2019 (2) Correction du second énoncé de l'examen du 22 octobre 2019. L'énoncé propose une façon de disposer des tables carrées dans une salle carrée. End of explanation def distance_table(x1, y1, x2, y2): ...
4,734
Given the following text description, write Python code to implement the functionality described below step by step Description: Raw Data Thresholding Exploration A slice at z=0 for reference Step1: Our Previous Method Step2: This result initially seemed reasonable. But, as a sanity check, we naively thresholded the...
Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pickle import sys sys.path.insert(0,'../code/functions/') import connectLib as cLib import plosLib as pLib import mouseVis as mv import tiffIO as tIO data0 = tIO.unzipChannels(tIO.loadTiff('../data/SEP-GluA1-...
4,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Verifying Central Limit Theorem in regression Step1: Synthesize the dataset Create 1000 random integers between 0, 100 for X and create y such that $$ y = \beta_{0} + \beta_{1}X + \epsilon ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import warnings warnings.filterwarnings('ignore') Explanation: Verifying Central Limit Theorem in regression End of explanation rand_1kx = np.random.randint(0,100,1000) x_mean = np.mean(rand_1kx)...
4,736
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook demonstrates how to use the classes in haloanalysis.model to perform likelihood scans of the IGMF parameter space. To start we construct the following Step1: The CascLike cla...
Python Code: %matplotlib inline from astropy.table import Table import matplotlib.pyplot as plt import matplotlib.cm from fermipy.spectrum import PLExpCutoff from fermipy.castro import CastroData from haloanalysis.model import make_prim_model, make_casc_model from haloanalysis.model import CascModel, CascLike from halo...
4,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: 1. Collect Wikipedia data about Olympic Games 2020 The idea of this project is to create a question answering model, based on a few paragraphs of provided text. Base GPT-3 models do a...
Python Code: import pandas as pd import wikipedia def filter_olympic_2020_titles(titles): Get the titles which are related to Olympic games hosted in 2020, given a list of titles titles = [title for title in titles if '2020' in title and 'olympi' in title.lower()] return titles def get_wiki_p...
4,738
Given the following text description, write Python code to implement the functionality described below step by step Description: SNR Benefits of Non-Uniform Scalar Quantization This code is provided as supplementary material of the lecture Quellencodierung. This code illustrates * Uniform scalar quantization of audio ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import librosa import librosa.display import IPython.display as ipd Explanation: SNR Benefits of Non-Uniform Scalar Quantization This code is provided as supplementary material of the lecture Quellencodierung. This code illustrates * Uni...
4,739
Given the following text description, write Python code to implement the functionality described below step by step Description: This entire theory is built on the idea that everything is normalized as input into the brain. i.e. all values are between 0 and 1. This is necessary because the learning rule has an adaptiv...
Python Code: p = GMM([1.0], np.array([[0.5,0.05]])) num_samples = 1000 beg = 0.0 end = 1.0 t = np.linspace(beg,end,num_samples) num_neurons = len(p.pis) colors = [np.random.rand(num_neurons,) for i in range(num_neurons)] p_y = p(t) p_max = p_y.max() np.random.seed(20) num_neurons = 9 network = Net(1,1,num_neurons, bias...
4,740
Given the following text description, write Python code to implement the functionality described below step by step Description: Coverage characterization using GenomeCov class (sequana.bedtools module) <center>http Step1: Read a Coverage file in BED format Step2: Select one chromosome (there is only one in this cas...
Python Code: %pylab inline from sequana import GenomeCov, sequana_data rcParams['figure.figsize'] = (10,6) Explanation: Coverage characterization using GenomeCov class (sequana.bedtools module) <center>http://sequana.readthedocs.org</center> Author: Thomas Cokelaer 2016-2018 Illustrative example of the Coverage module ...
4,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing In Context Social Sciences Track Lecture 4--topics, trends, and dimensional scaling Matthew L. Jones Step1: Reading at scale Step2: IMPORTANT Step3: Let's keep using the remarka...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt Explanation: Computing In Context Social Sciences Track Lecture 4--topics, trends, and dimensional scaling Matthew L. Jones End of explanation from IPython.display import Image Image("http://journalofdigitalhumanities.org/wp-content/upl...
4,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Usage Step1: Find from the texts Step2: frequent serial episodes which consist of words üks and kaks. Find frequent episodes Let the width of the Winepi window be 31 characters and the mi...
Python Code: from episode_miner import EventText, EventSequences, Episode, Episodes from estnltk.taggers import EventTagger from IPython.display import HTML, FileLink Explanation: Usage End of explanation event_vocabulary = [{'term': 'üks'}, {'term': 'kaks'}] event_tagger = EventTagger(event_vo...
4,743
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="#Motivation" data-toc-modified-id="Motivation-1"><span class="toc-item-num">1...
Python Code: from collections import OrderedDict # values entered manually from https://brandlive.here.com/colors here_primary_cols = OrderedDict( HERE_Aqua = '#48dad0', HERE_Aqua_UNKNOWN = '#00908a', # unknown status, maybe an error? HERE_Aqua_Dark = '#00afaa', HERE_Aqua_75 = '#76e3dc',...
4,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Original paper Step1: Make sure that the values of real and generated data are of the same order - it is important for cooperative binarizing Step2: 1. Binarize# To understand how real and...
Python Code: import math import numpy as np import matplotlib.pyplot as plt import matplotlib.lines as mlines import matplotlib import torch import sklearn CHANNEL_NUM = 3 PICTURE_SIZE = 36 class ParticleDataset(): def __init__(self, file): self.data = np.load(file) self.image = self.data['Pictures'...
4,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a new Materials Commons project This example demonstrates creating a new Materials Commons project from a Jupyter notebook. To try running it locally, download the notebook from here....
Python Code: # Login information (Edit here or be prompted by the next cell) email = None mcurl = "https://materialscommons.org/api" # Construct a Materials Commons client from materials_commons.cli.user_config import make_client_and_login_if_necessary if email is None: print("Account (email):") email = input()...
4,746
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth for Free Input Tasks Step1: Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this, we need to...
Python Code: import pandas as pd test_data = pd.read_csv("../data/person-video-free-input.csv") test_data.head() Explanation: CrowdTruth for Free Input Tasks: Person Annotation in Video In this tutorial, we will apply CrowdTruth metrics to a free input crowdsourcing task for Person Annotation from video fragments. The ...
4,747
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 1 Imports Step2: Checkerboard Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0 Step3: Use vizarray to visualize a checker...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va Explanation: Numpy Exercise 1 Imports End of explanation def checkerboard(size): Return a 2d checkboard of 0.0 and 1.0 as a NumPy array a=np.zer...
4,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-worker training with Keras Learning Objectives Multi-worker Configuration Choose the right strategy Train the model Multi worker training in depth Introduction This notebook demonstrat...
Python Code: import json import os import sys Explanation: Multi-worker training with Keras Learning Objectives Multi-worker Configuration Choose the right strategy Train the model Multi worker training in depth Introduction This notebook demonstrates multi-worker distributed training with Keras model using tf.distribu...
4,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 DeepMind Technologies Limited. 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 ...
Python Code: !apt-get install libsdl2-dev !apt-get install libosmesa6-dev !apt-get install libffi-dev !apt-get install gettext !apt-get install python3-numpy-dev python3-dev Explanation: Copyright 2021 DeepMind Technologies Limited. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this fi...
4,750
Given the following text description, write Python code to implement the functionality described below step by step Description: A notebook to test and demonstrate the MMD test of Gretton et al., 2012 used as a goodness-of-fit test. Require the ability to sample from the density p. Step1: MMD test (as a goodness-of-f...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline #%config InlineBackend.figure_format = 'svg' #%config InlineBackend.figure_format = 'pdf' import freqopttest.tst as tst import kgof import kgof.data as data import kgof.density as density import kgof.goftest as gof import kgof.mmd as mgof import kgof.ke...
4,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Bins Mark This Mark is essentially the same as the Hist Mark from a user point of view, but is actually a Bars instance that bins sample data. The difference with Hist is that the binning is...
Python Code: # Create a sample of Gaussian draws np.random.seed(0) x_data = np.random.randn(1000) Explanation: Bins Mark This Mark is essentially the same as the Hist Mark from a user point of view, but is actually a Bars instance that bins sample data. The difference with Hist is that the binning is done in the backen...
4,752
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to Experimental Design with Emukit Overview Step1: Navigation What is experimental design? The ingredients of experimental design Emukit's experimental design interface Refe...
Python Code: # General imports %matplotlib inline import numpy as np import matplotlib.pyplot as plt from matplotlib import colors as mcolors # Figure config LEGEND_SIZE = 15 Explanation: An Introduction to Experimental Design with Emukit Overview End of explanation from emukit.test_functions import forrester_function ...
4,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Basic Functions Step1: Build In Constants <ul> <li>False</li> <li>True</li> <li>None -> Represents absence of a value</li> <li>NotImplememted -> Returned by some functions when the a...
Python Code: abs(-3) # Gives the absolute value of a variable all([1,2,3,0]) # Returns True if all iterators are true. any([1,2,3,4,0]) # If any value is true among the iterators def prime(): pass print(callable(prime)) # Returns True if object has a return statement # instances of classes are callable if they hav...
4,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, notebook style sheet by L.A. Barba, N.C. Clementi Step1: Viscoelastic stre...
Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) # Import Libraries # ---------------- import numpy as np from numba import jit import matplotlib import matplotlib.pyplot as plt fr...
4,755
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Python and MySQL tutorial </center> <center> Author Step1: Calculator Step2: Strings Step3: show ' and " in a string Step4: span multiple lines Step5: slice and index Step6: I...
Python Code: width = 20 height = 5*9 width * height Explanation: <center> Python and MySQL tutorial </center> <center> Author: Cheng Nie </center> <center> Check chengnie.com for the most recent version </center> <center> Current Version: Feb 12, 2016</center> Python Setup Since most students in this class use Windows ...
4,756
Given the following text description, write Python code to implement the functionality described below step by step Description: To run this sample on Google Cloud Platform with various accelerator setups Step1: Overview This notebook is a fork of the Geting started notebook for the Jigsaw Multilingual Toxic Comment ...
Python Code: # When not running on Kaggle, comment out this import from kaggle_datasets import KaggleDatasets # When not running on Kaggle, set a fixed GCS path here GCS_PATH = KaggleDatasets().get_gcs_path('jigsaw-multilingual-toxic-comment-classification') print(GCS_PATH) Explanation: To run this sample on Google Clo...
4,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fisheries competition In this notebook we're going to investigate a range of different architectures for the Kaggle fisheries competition. We use VGG with batch normalization through...
Python Code: import torch import torchvision.models as models import torchvision.transforms as transforms import torchvision.datasets as datasets from torchvision.utils import make_grid from PIL import Image import matplotlib.pyplot as plt import torch.nn as nn import torch.optim as optim import torch.utils.trainer as ...
4,758
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction From v2.8.0, pymatgen comes with a fairly robust system of managing units. In essence, subclasses of float and numpy array is provided to attach units to any quantity, as well a...
Python Code: import pymatgen as mg #The constructor is simply the value + a string unit. e = mg.Energy(1000, "Ha") #Let's perform a conversion. Note that when printing, the units are printed as well. print "{} = {}".format(e, e.to("eV")) #To check what units are supported print "Supported energy units are {}".format(e....
4,759
Given the following text description, write Python code to implement the functionality described below step by step Description: Non linear curve fitting with python Germain Salvato Vallverdu germain.vallverdu@univ-pau.fr This cookbook presents how to fit a non linear model on a set of data using python. Two kind of a...
Python Code: # manage data and fit import pandas as pd import numpy as np # first part with least squares from scipy.optimize import curve_fit # second part about ODR from scipy.odr import ODR, Model, Data, RealData # style and notebook integration of the plots import seaborn as sns %matplotlib inline sns.set(style="w...
4,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab Part II Step1: Our model will be like this Step2: Step 2 Step3: Step 3 Step4: Step 4 Step5: Step 5 Step6: Step 6 Step7: Step 7 Step8: Solutions
Python Code: import math import pickle as p import tensorflow as tf import numpy as np import utils import json Explanation: Lab Part II: RNN Sentiment Classifier In the previous lab, you built a tweet sentiment classifier with a simple feedforward neural network. Now we ask you to improve this model by representing it...
4,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Download Test Data for XBRAIN This notebook will walk through on how to download the test data necessary for the demo Last Update Step1: Methods Step2: Parameters to pass to Google Drive S...
Python Code: # imports import requests import zipfile import os Explanation: Download Test Data for XBRAIN This notebook will walk through on how to download the test data necessary for the demo Last Update: 10/12/2017 End of explanation # Methods to pull from google drive def download_file_from_google_drive(id, destin...
4,762
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook contains code to train a fully connected neural network on MNIST using tf.contrib.learn. At the end is a short exercise. Step1: Import the dataset Step2: There are 55k exampl...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf learn = tf.contrib.learn tf.logging.set_verbosity(tf.logging.ERROR) Explanation: This notebook contains code to train a fully connected neural network on MNIST using tf.contrib.learn. At the end is a short exercis...
4,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy 是 Python 数据分析的基础,很多有关Python数据分析都是建立在其之上。 1 ndarray 整个 numpy 的基础是 ndarray (n dimensional array),表示同一元素组成的多维数组。 + dtype 数据类型 + shape 由N个正整数组成的元组,每一个元素代表了每一维的大小 + axes 数组的维数为轴,轴的数量为秩(ran...
Python Code: import numpy as np a = np.array([1,2,3]) print a type(a) type(a) a.dtype print a.ndim print a.size print a.shape Explanation: Numpy 是 Python 数据分析的基础,很多有关Python数据分析都是建立在其之上。 1 ndarray 整个 numpy 的基础是 ndarray (n dimensional array),表示同一元素组成的多维数组。 + dtype 数据类型 + shape 由N个正整数组成的元组,每一个元素代表了每一维的大小 + axes 数组的维数为轴,轴...
4,764
Given the following text description, write Python code to implement the functionality described below step by step Description: 2018-01-12 / FMA sub-sampling Problem statement Step1: Binary thresholding Step2: Step3: Multi-valued thresholds
Python Code: import numpy as np import pandas as pd import entrofy import matplotlib.pyplot as plt %matplotlib nbagg df = pd.read_csv('/home/bmcfee/data/vggish-likelihoods-a226b3-maxagg10.csv.gz', index_col=0) df.head(5) (df >= 0.5).describe().T.sort_values('freq') df.median() Explanation: 2018-01-12 / FMA sub-sampling...
4,765
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). Neural Machine Translation with Attention <table class="tfo-notebook-buttons" align="le...
Python Code: from __future__ import absolute_import, division, print_function # Import TensorFlow >= 1.10 and enable eager execution import tensorflow as tf tf.enable_eager_execution() import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import unicodedata import re import numpy as np im...
4,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Breast Cancer Proliferation Scores with Apache Spark and Apache SystemML Machine Learning Setup Step1: Read in train & val data Step2: Extract X and Y matrices Step4: Convert t...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os import matplotlib.pyplot as plt import numpy as np from pyspark.sql.functions import col, max import systemml # pip3 install systemml from systemml import MLContext, dml plt.rcParams['figure.figsize'] = (10, 6) ml = MLContext(sc) Explanation:...
4,767
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', 'bnu', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: BNU Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Proper...
4,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Implementing a denoising autoencoder Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submis...
Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflo...
4,769
Given the following text description, write Python code to implement the functionality described below step by step Description: Automated finite difference operators from symbolic equations This notebook is the first in a series of hands-on tutorial notebooks that are intended to give a brief practical overview of th...
Python Code: from devito import * from sympy import init_printing, symbols, solve init_printing(use_latex=True) Explanation: Automated finite difference operators from symbolic equations This notebook is the first in a series of hands-on tutorial notebooks that are intended to give a brief practical overview of the Dev...
4,770
Given the following text description, write Python code to implement the functionality described below step by step Description: Datasets Step1: The default query terms are 'big data', 'data science' and 'machine learning'. The dictionary returned from the call contains the standard 'X' and 'y' keys that are ready to...
Python Code: import pods %matplotlib inline # calling without arguments uses the default query terms data = pods.datasets.google_trends() Explanation: Datasets: Downloading Data from Google Trends 28th May 2014 Neil Lawrence This data set collection was inspired by a ipython notebook from sahuguet which made queries t...
4,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Example for using the WindpowerlibTurbine model The WindpowerlibTurbine model can be used to determine the feed-in of a wind turbine using the windpowerlib. The windpowerlib is a python libr...
Python Code: from feedinlib import WindPowerPlant Explanation: Example for using the WindpowerlibTurbine model The WindpowerlibTurbine model can be used to determine the feed-in of a wind turbine using the windpowerlib. The windpowerlib is a python library for simulating the performance of wind turbines and farms. For ...
4,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Summarizing Multiple Graphs Together Author Step1: Environment Step2: Dependencies Step3: Setup Step4: Data In this notebook, pickled instances of networks from the Causal Biological Net...
Python Code: import os import time import sys import pybel import pybel_tools from pybel_tools.summary import info_str Explanation: Summarizing Multiple Graphs Together Author: Charles Tapley Hoyt Estimated Run Time: 45 seconds This notebook shows how to combine multiple graphs from different sources and summarize them...
4,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the previous tutorial, you learned how to build an agent with one-step lookahead. This agent performs reasonably well, but definitely still has room for improvement! For in...
Python Code: #$HIDE_INPUT$ import random import numpy as np # Gets board at next step if agent drops piece in selected column def drop_piece(grid, col, mark, config): next_grid = grid.copy() for row in range(config.rows-1, -1, -1): if next_grid[row][col] == 0: break next_grid[row][col] =...
4,774
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow TensorFlow is an open source library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the mu...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import tensorflow as tf Explanation: TensorFlow TensorFlow is an open source library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensi...
4,775
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...
4,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Elements are the basic building blocks for any HoloViews visualization. These are the objects that can be composed together using the various Container types. Here in this overview, we show...
Python Code: import holoviews as hv hv.notebook_extension() hv.Element(None, group='Value', label='Label') Explanation: Elements are the basic building blocks for any HoloViews visualization. These are the objects that can be composed together using the various Container types. Here in this overview, we show an exampl...
4,777
Given the following text description, write Python code to implement the functionality described below step by step Description: A workflow for classifying a point cloud using point features The following example will run through the functions to classify a point cloud based on the point neighborhood attributes. This ...
Python Code: from geospatial_learn import learning as ln incloud = "/path/to/Llandinam.ply" Explanation: A workflow for classifying a point cloud using point features The following example will run through the functions to classify a point cloud based on the point neighborhood attributes. This is a very simple example ...
4,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Route Computation and Analysis using Batfish Network engineers routinely need to validate routing and forwarding in the network. They often do that by connecting to multiple ...
Python Code: # Import packages %run startup.py bf = Session(host="localhost") Explanation: Introduction to Route Computation and Analysis using Batfish Network engineers routinely need to validate routing and forwarding in the network. They often do that by connecting to multiple network devices and executing a series ...
4,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Spots in PHOEBE 2 vs PHOEBE Legacy Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your inst...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Comparing Spots in PHOEBE 2 vs PHOEBE Legacy Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of expla...
4,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Jupyter Notebooks Step1: A continuación usaremos una celda de código en la cual guardaremos una expresión markdown en una variable python para su posterior visualización. Step2: El método ...
Python Code: from IPython.display import display, Latex, Markdown Explanation: Jupyter Notebooks: Intermedio Jupyter permite integrar sus capacidades de visualización html con el modulo IPython.display. De esta forma se puede generar la visualización de texto, imagen, video y ecuaciones de una forma sistematica al inte...
4,781
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Assignment 3a Step2: Working with external modules Exercise 2 NLTK offers a way of using WordNet in Python. Do some research (using google, because quite frankly, tha...
Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unzip images.zip -d ....
4,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Select seeds for search networks I select small (1000-1500) sized bot network and pick 4 random members from it Step1: Now search for friends of seed users Step2: Show common users in tota...
Python Code: seeds = ['volya_belousova', 'egor4rgurev', 'kirillfrolovdw', 'ilyazhuchhj'] auth = tweepy.OAuthHandler(OAUTH_KEY, OAUTH_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) graph = Graph(user=NEO4J_USER, password=NE...
4,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Summary Requirements Step8: 1. Make a request Only the mapping *id -> name * Step9: Full response Step10: 2. Bulk request If you need to retrieve more than 100 mappings, you will need to ...
Python Code: from pynexus import AppNexusAPI APPNEXUS_ACCOUNT = { "username": "", "password": "" } api = AppNexusAPI(**APPNEXUS_ACCOUNT) Explanation: Summary Requirements: python 3 This notebook show how to make call to the AppNexus API. Implemented functions: ```python def get_campaign(self, ids=None, one...
4,784
Given the following text description, write Python code to implement the functionality described below step by step Description: Generator expressions Step1: Tuples as Records Step2: Tuple Unpacking Step3: Named tuples Step5: Slicing Step6: Assigning to Slices Step7: Using + and * with Sequences Step8: Building...
Python Code: symbols = '$#%^&' [ord(s) for s in symbols] tuple(ord(s) for s in symbols) (ord(s) for s in symbols) for x in (ord(s) for s in symbols): print(x) import array array.array('I', (ord(s) for s in symbols)) colors = ['black', 'white'] sizes = ['S', 'M', 'L'] for tshirt in ((c, s) for c in colors for s in s...
4,785
Given the following text description, write Python code to implement the functionality described below step by step Description: MPB mode-solver MPB is a free open source sofware to compute Step1: As you can see the refractive index goes from 1.44 SiO2 Silicon dioxide to 3.47 Silicon. Step2: As you can see the first...
Python Code: import numpy as np import matplotlib.pyplot as plt import meep as mp import gdsfactory.simulation.modes as gm modes = gm.find_modes_waveguide( parity=mp.NO_PARITY, wg_width=0.4, ncore=3.47, nclad=1.44, wg_thickness=0.22, resolution=40, sy=3, sz=3, nmodes=4, ) m1 = modes[...
4,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Project Euler Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. Step4: Now define a count_letters(n) that return...
Python Code: import numpy as np def number_to_words(n): Given a number n between 1-1000 inclusive return a list of words for the number. # YOUR CODE HERE #raise NotImplementedError() ones=['one','two','three','four','five','six','seven','eight','nine','ten'] teens=['eleven','twelve','thirteen','four...
4,787
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...
4,788
Given the following text description, write Python code to implement the functionality described below step by step Description: hot-CNO and breakout Step1: This collection of rates has the main CNO rates plus a breakout rate into the hot CNO cycle Step2: To evaluate the rates, we need a composition. This is define...
Python Code: import pynucastro as pyrl Explanation: hot-CNO and breakout End of explanation files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13--c13-wc12", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12", ...
4,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Unsupervised Analysis of Days of Week Tresting crossings each dat as features to learn about the relationships bwteen days of the week Step1: Get Data Step2: Principal Component Analysis S...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn') import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture Explanation: Unsupervised Analysis of Days of Week Tresting crossings each dat as features to learn about the ...
4,790
Given the following text description, write Python code to implement the functionality described below step by step Description: ## <p style="text-align Step1: Control flow commands Step2: numpy Step3: matplotlib
Python Code: # Basic python print("Hello world!") print(type("Hello world!")) print(type("Hello world!")==str) # dir() # Built-in data types # int print(type(1)) # float print(type(1.0)) # str print(type("Hello World")) # bool print(type(False)) # Built-in data types: list alist = [1, 2.0, "3"] print(alist) print(type(...
4,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph format The EDeN library allows the vectorization of graphs, i.e. the transformation of graphs into sparse vectors. The graphs that can be processed by the EDeN library have the followi...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 from eden.util import configure_logging import logging logger = logging.getLogger() configure_logging(logger,verbosity=1) import pylab as plt import networkx as nx G=nx.Graph() G.add_node(0, label='A') G.add_node(1, label='B') G.add_node(2, label='C') G...
4,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Load a sample of the raw JSON data into pandas. Step1: Transform the full JSON file into a CSV, removing any stuff that we won't need Step3: Creates CSVs of text from comments made by user...
Python Code: import pandas as pd json_file = 'sample_data' list(pd.read_json(json_file, lines=True)) Explanation: Load a sample of the raw JSON data into pandas. End of explanation import csv import json from nltk.tokenize import TweetTokenizer from tqdm import tqdm MIN_NUM_WORD_TOKENS = 10 TOTAL_NUM_LINES = 53851542 ...
4,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Negative Binomial Regression (Students absence example) Negative binomial distribution review I always experience some kind of confusion when looking at the negative binomial distribution af...
Python Code: import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import nbinom az.style.use("arviz-darkgrid") import warnings warnings.simplefilter(action='ignore', category=FutureWarning) Explanation: Negative Binomial Regression (Students abse...
4,794
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Fourier Transform Let's download an audio file Step1: Listen to the audio file Step2: Fourier Transform The Fourier Transform (Wikipedia) is one of the most fundamenta...
Python Code: import urllib filename = 'c_strum.wav' urllib.urlretrieve('http://audio.musicinformationretrieval.com/c_strum.wav', filename=filename) x, sr = librosa.load(filename) print(x.shape) print(sr) Explanation: &larr; Back to Index Fourier Transform Let's download an audio file: End of explanation ipd.Audio(x, ra...
4,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Digits Dataset Step2: Split Into Training And Test Sets Step3: Fit Standardizer To Training Set Step4: Apply Standardizer To Training And Test Sets
Python Code: # Load libraries from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split Explanation: Title: Split Data Into Training And Test Sets Slug: split_data_into_training_and_test_sets Summary: How to split data into training and test sets ...
4,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Step12: Module is an abstract class which defines fundamental methods necessary for a training a neural network. You do not need to change anything here, just read the comments. Step19: Seq...
Python Code: class Module(object): def __init__ (self): self.output = None self.gradInput = None self.training = True Basically, you can think of a module as of a something (black box) which can process `input` data and produce `ouput` data. This is like applying a function...
4,797
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient reversal pytorch Inspired from the following tweets Step1: Tensorflow implementation Step2: Modify the gradients Keep forward pass the same. The trick is to add $g(x)$, such that...
Python Code: import torch import tensorflow as tf from torch.autograd import Variable import numpy as np def f(X): return X*X def g(X): return X**3 X = np.random.randn(10) X Explanation: Gradient reversal pytorch Inspired from the following tweets: https://twitter.com/mat_kelcey/status/932149793765261313 https:...
4,798
Given the following text description, write Python code to implement the functionality described below step by step Description: ============================================================================= E E||---|---|-G-|---|-A-|---|---|-C-|---|-D-|---|-E-|---|---|-G-|---|-A-|---|---| B ||-C-|---|-D-|---|-...
Python Code: from fretboard import * c = Note('C') print (c) Note('C#') Note('Db') Note('B#') Explanation: ============================================================================= E E||---|---|-G-|---|-A-|---|---|-C-|---|-D-|---|-E-|---|---|-G-|---|-A-|---|---| B ||-C-|---|-D-|---|-E-|---|---|-G-|---|-A-|...
4,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Euplotid says "hello world" Markdown hello world hello world hello world Step1: Quick Jupyter Tips select how the cell is interpreted in the toolbar at the top, this one says "Markdown" vie...
Python Code: #comments which are not run are denoted with # #hello world #try running this cell clicking inside it and pressing shift+enter #python3 print("hello world") Explanation: Euplotid says "hello world" Markdown hello world hello world hello world End of explanation %lsmagic #shows you all available magics, the...