Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
13,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Quickstart This notebook was made with the following version of emcee Step1: The easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annota...
Python Code: import emcee emcee.__version__ Explanation: Quickstart This notebook was made with the following version of emcee: End of explanation import numpy as np Explanation: The easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annotated, fully-functional example...
13,701
Given the following text description, write Python code to implement the functionality described below step by step Description: 1 Make a request from the Forecast.io API for where you were born (or lived, or want to visit!) Tip Step1: 2. What's the current wind speed? How much warmer does it feel than it actually is...
Python Code: #https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME response = requests.get('https://api.forecast.io/forecast/4da699cf85f9706ce50848a7e59591b7/12.971599,77.594563') data = response.json() #print(data) #print(data.keys()) print("Bangalore is in", data['timezone'], "timezone") timezone_find = da...
13,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 2 Imports Step1: Exoplanet properties Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the propertie...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 2 Imports End of explanation !head -n 30 open_exoplanet_catalogue.txt Explanation: Exoplanet properties Over the past few decades, astronomers have discovered thousands of extrasolar planets. The followin...
13,703
Given the following text description, write Python code to implement the functionality described below step by step Description: =================================================================== Support Vector Regression (SVR) using linear and non-linear kernels ======================================================...
Python Code: print(__doc__) import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt Explanation: =================================================================== Support Vector Regression (SVR) using linear and non-linear kernels ================================================================...
13,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Stock Prices Step1: Ridge as Linear Regressor
Python Code: from sklearn.linear_model import RidgeCV from sklearn.model_selection import train_test_split from sklearn.externals import joblib import numpy as np import matplotlib.pyplot as plt import os data = np.loadtxt(fname = 'data.txt', delimiter = ',') X, y = data[:,:5], data[:,5] print("Features sample: {}".for...
13,705
Given the following text description, write Python code to implement the functionality described below step by step Description: GLM Step1: Generating data Create some toy data to play around with and scatter-plot it. Essentially we are creating a regression line defined by intercept and slope and add data points by...
Python Code: %matplotlib inline from pymc3 import * import numpy as np import matplotlib.pyplot as plt Explanation: GLM: Linear regression Author: Thomas Wiecki This tutorial is adapted from a blog post by Thomas Wiecki called "The Inference Button: Bayesian GLMs made easy with PyMC3". This tutorial appeared as a post...
13,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactive Network Exploration with pynucastro This notebook shows off the interactive RateCollection network plot. You must have widgets enabled. Jupyter notebook Step1: This collection o...
Python Code: %matplotlib inline import pynucastro as pyrl Explanation: Interactive Network Exploration with pynucastro This notebook shows off the interactive RateCollection network plot. You must have widgets enabled. Jupyter notebook: jupyter nbextension enable --py --user widgetsnbextension for a user install or...
13,707
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate terminated results Exiobase v.3.3.11b1 exc. iLUC, electricity markets and social extensions Investments are not integrated in the MR_HIOT table. They are accounted for in the Final...
Python Code: HIOT_FD = "/Users/marie/Desktop/MR_HIOT_2011_v3.3.11.xlsx" import pandas as pd import csv ### MR-HIOT.csv is created because the excel is too heavy data_xls = pd.read_excel(HIOT_FD, 'HIOT', index_col=None) data_xls.to_csv('MR_HIOT.csv', encoding='utf-8') ### FD.csv is created because the excel is too heavy...
13,708
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="#Generating-synthetic-data" data-toc-modified-id="Generating-synthetic-data-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Generat...
Python Code: # important stuff: import os import pandas as pd import numpy as np import statsmodels.tools.numdiff as smnd import scipy # Graphics import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns from matplotlib import rc rc('text', usetex=True) rc('text.latex', preamble=r'\usepackage{cmbri...
13,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifa...
13,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Imaging Cortical Layers Step1: Extract images from the imaging site of our proposed cortical layers
Python Code: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt #%matplotlib inline import numpy as np import urllib2 import scipy.stats as stats np.set_printoptions(precision=3, suppress=True) url = ('https://raw.githubusercontent.com/Upward-Spiral-Science' '/data/master/syn-density/output...
13,711
Given the following text description, write Python code to implement the functionality described below step by step Description: Revised version Step1: Step 4a Step2: Step 4b Step3: Step 5 Step4: Apply to data
Python Code: import numpy as np from scipy import stats import matplotlib.pyplot as plt import itertools import urllib2 import scipy.stats as stats %matplotlib inline np.set_printoptions(precision=3, threshold=1000000, suppress=True) np.random.seed(1) alpha = .025 url = ('https://raw.githubusercontent.com/Upward-Spiral...
13,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing MusicBrainz data with Python/JS, an introduction This introductory notebook will explain how I get database from MusicBrainz and how I transform it to Python format for display i...
Python Code: %load_ext watermark %watermark --python -r %watermark --date --updated Explanation: Visualizing MusicBrainz data with Python/JS, an introduction This introductory notebook will explain how I get database from MusicBrainz and how I transform it to Python format for display in tables or plots. A static HTML ...
13,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 01 Big Data Ingesting Step1: The next step will be to copy the data file that we will be using for this tutorial into the same folder as these notes. We will be looking at a couple of...
Python Code: import pandas as pd Explanation: Class 01 Big Data Ingesting: CSVs, Data frames, and Plots Welcome to PHY178/CSC171. We will be using the Python language to import data, run machine learning, visualize the results, and communicate those results. Much of the data that we will use this semester is stored in ...
13,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to PyTorch Introduction to Torch's tensor library All of deep learning is computations on tensors, which are generalizations of a matrix that can be indexed in more than 2 dimen...
Python Code: # Author: Robert Guthrie import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) Explanation: Introduction to PyTorch Introduction to Torch's tensor library All of deep learning is computations on tensors, which a...
13,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power estimate by projecting the covariance with MNE We can apply the MNE inverse operator to a covariance matrix to obtain an estimate of source power. This is computationall...
Python Code: # Author: Denis A. Engemann <denis-alexander.engemann@inria.fr> # Luke Bloy <luke.bloy@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse_cov data_path = sample.d...
13,716
Given the following text description, write Python code to implement the functionality described below step by step Description: The objective of this notebook is to show how to read and plot data from a mooring (time series). Step1: Data reading The data file is located in the datafiles directory. Step2: As the pla...
Python Code: %matplotlib inline import netCDF4 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import rcParams from matplotlib import colors from mpl_toolkits.basemap import Basemap Explanation: The objective of this notebook is to show how to read and plot data from a moorin...
13,717
Given the following text description, write Python code to implement the functionality described below step by step Description: CCSDT theory for a closed-shell reference This notebook extends the spinorbital-CCSD notebook to compute CCSDT Step1: Read calculation information (integrals, number of orbitals) We start b...
Python Code: import time import wicked as w import numpy as np from examples_helpers import * Explanation: CCSDT theory for a closed-shell reference This notebook extends the spinorbital-CCSD notebook to compute CCSDT End of explanation molecule = "sr-h6-sto-3g" with open(f"{molecule}.npy", "rb") as f: Eref = np.lo...
13,718
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, I will show how to train the TensorFlow version of Sketch-RNN on a new dataset, and convert the weights of the TF model to a JSON format that is usable by Sketch-RNN-JS so ...
Python Code: # import the required libraries import numpy as np import time import random import codecs import collections import os import math import json import tensorflow as tf from six.moves import xrange # libraries required for visualisation: from IPython.display import SVG, display import svgwrite # conda insta...
13,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo for NitroML on Cloud using KubeFlow Step 1 Step1: Step 2 Step2: Step 3 Step3: Step 4 Step4: Step 5 Step5: Step 6
Python Code: import sys # install kfp (https://kubeflow-pipelines.readthedocs.io/en/latest/source/kfp.html) !{sys.executable} -m pip install --user --upgrade -q kfp==1.0.0 !{sys.executable} -m pip install --user --upgrade -q kfp-server-api==1.0.0 # Download skaffold and set it executable. # !curl -Lo skaffold https://s...
13,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Polara for custom evaluation scenarios Polara is designed to automate the process of model prototyping and evaluation as much as possible. As a part of it, <div class="alert alert-bloc...
Python Code: import numpy as np from polara.datasets.movielens import get_movielens_data seed = 0 def random_state(seed=seed): # to fix random state in experiments return np.random.RandomState(seed=seed) Explanation: Using Polara for custom evaluation scenarios Polara is designed to automate the process of model pr...
13,721
Given the following text description, write Python code to implement the functionality described below step by step Description: 4.2 サードパーティ製パッケージを使ってスクレイピングに挑戦 Requests http Step1: RequestsでWebページを取得 Step2: Requestsを使いこなす connpass APIリファレンス https Step3: httpbin(1) Step4: Beautiful Soup 4を使いこなす
Python Code: import requests import bs4 Explanation: 4.2 サードパーティ製パッケージを使ってスクレイピングに挑戦 Requests http://docs.python-requests.org/ Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ End of explanation # Requestsでgihyo.jpのページのデータを取得 import requests r = requests.get('http://gihyo.jp/lifestyle/clip/01/everyday-cat')...
13,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrices de Transformación Las matrices de rotación y traslación nos sirven para transformar una coordenada entre diferentes sistemas coordenados, pero tambien lo podemos ver, como la transf...
Python Code: from math import pi, sin, cos from numpy import matrix from matplotlib.pyplot import figure, plot, style from mpl_toolkits.mplot3d import Axes3D style.use("ggplot") %matplotlib notebook τ = 2*pi Explanation: Matrices de Transformación Las matrices de rotación y traslación nos sirven para transformar una co...
13,723
Given the following text description, write Python code to implement the functionality described below step by step Description: II. Numpy and Scipy Numpy contains core routines for doing fast vector, matrix, and linear algebra-type operations in Python. Scipy contains additional routines for optimization, special fun...
Python Code: %pylab inline import numpy as np # Import pylab to provide scientific Python libraries (NumPy, SciPy, Matplotlib) %pylab --no-import-all #import pylab as pl # import the Image display module from IPython.display import Image import math np.array([1,2,3,4,5,6]) Explanation: II. Numpy and Scipy Numpy contain...
13,724
Given the following text description, write Python code to implement the functionality described below step by step Description: An example packet from ESEO. Step1: Trim the data between the 0x7e7e flags. We skip Reed-Solomon decoding, since we are confident that there are no bit errors. We remove the 16 Reed-Solomon...
Python Code: bits = np.array([0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0,...
13,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Core vision Basic image opening/processing functionality Helpers Step1: Image.n_px Image.n_px (property) Number of pixels in image Step2: Image.shape Image.shape (property) Image (height,w...
Python Code: #|export imagenet_stats = ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) cifar_stats = ([0.491, 0.482, 0.447], [0.247, 0.243, 0.261]) mnist_stats = ([0.131], [0.308]) im = Image.open(TEST_IMAGE).resize((30,20)) #|export if not hasattr(Image,'_patched'): _old_sz = Image.Image.size.fget @patch(...
13,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Eager Execution <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Now you can run TensorFlow ...
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,727
Given the following text description, write Python code to implement the functionality described below step by step Description: MRI intensity normalization Intensity normalization of multi-channel MRI images using the method proposed by Nyul et al. 2000. In the original paper, the authors suggest a method where a set...
Python Code: import os import numpy as np import nibabel as nib from nyul import nyul_train_standard_scale DATA_DIR = 'data_examples' T1_name = 'T1.nii.gz' MASK_name = 'brainmask.nii.gz' # generate training scans train_scans = [os.path.join(DATA_DIR, folder, T1_name) for folder in os.listdir(DATA_DIR)...
13,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Latent Dirichlet Allocation applied to real data Step1: Data fetching and preprocessing Building sample dataset We are considering a collection of English news articles about the case relat...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Latent Dirichlet Allocation applied to real data End of explanation #get raw data import xml.etree.ElementTree as ET tree = ET.parse('../dataset/nysk.xml') root = tree.getroot() root1 = root.getchildren()[150].getchildren() texts=...
13,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Tests of PySpark UDF with mapInArrow vs. mapInPandas Step1: Dataset preparation Step2: mapInPAndas tests Test 1 - dummy UDF Step3: Test 2 Step4: mapInArrow tests Test 3 Step5: Test 5 St...
Python Code: # This is a new feature, candidate from Spark 3.3.0 # See https://issues.apache.org/jira/browse/SPARK-37227 import findspark findspark.init("/home/luca/Spark/spark-3.3.0-SNAPSHOT-bin-spark_21220128") # use only 1 core to make performance comparisons easier/cleaner from pyspark.sql import SparkSession spark...
13,730
Given the following text description, write Python code to implement the functionality described below step by step Description: 1、随机生成1万个整数,范围在0-10万之间,分别进行简单选择排序、快速排序(自行递归实现的)以及内置sort函数3种排序,打印出3种排序的运行时间。 假设有快速排序算法quick_sort(seq),可以实现快速排序。 令left_seq = [], right_seq = [] 令待排序序列区间的第一个元素为p,即p=seq[0] 对seq的[start+1,end...
Python Code: import random import time def simple_sort(numbers): for i in range(len(numbers)): for j in range(i+1,len(numbers)): min=i if numbers[min]>numbers[j]: min=j numbers[i],numbers[min]=numbers[min],numbers[i] def quick_sort(seq): left_seq=[] ri...
13,731
Given the following text description, write Python code to implement the functionality described below step by step Description: United States carries most of the weight of the total electricity consumption in the household market in N. America in the perdio 1990-2014. US is followed in consumption by Canada and Mexic...
Python Code: #Europe df5 = df4.loc[df4.index.isin(['Austria', 'Belgium', 'Bulgaria','Croatia', 'Cyprus', 'Czechia','Denmark', 'Estonia','Finland','France','Germany','Greece','Hungary','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Netherlands','Poland','Portugal','Romania','Slovakia', 'Slovenia','Spain', ...
13,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Hyper-study The time series models built with the help of bayesloop are called hierarchical models, since the parameters of the observation model are in turn controlled by hyper-parameters t...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # plotting import seaborn as sns # nicer plots sns.set_style('whitegrid') # plot styling import numpy as np import bayesloop as bl S = bl.HyperStudy() S.loadExampleData() L = bl.om.Poisson('accident_rate', bl.oint(0, 6, 1000)) T = bl.tm.Seri...
13,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Functions 1. pairwise_correlation( df ) Step3: 2. corr_rowi_rowj( df , i , j ) Step5: 3. corr_rowi_vs_all1( df ) Step7: 4. corr_rowi_vs_all2( df , i ) Step8: Test 1. pairwise_corr...
Python Code: #Try now def pairwise_correlation(df): #Print data first to make it easy to check. print("data:") print(df,"\n\nP value:") metrix = pd.DataFrame() labels=[] #Use 'iterrows()' to get rows repeatedly. #There are two for loops. The outer for loop is used to get...
13,734
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2 Step1: Note Step2: Problem set 1 Step3: Problem set 2 Step4: Nicely done. Now, in the cell below, fill in the indicated string with a SQL statement that returns all occupation...
Python Code: import pg8000 conn = pg8000.connect(database="homework2") Explanation: Homework 2: Working with SQL (Data and Databases 2016) This homework assignment takes the form of an IPython Notebook. There are a number of exercises below, with notebook cells that need to be completed in order to meet particular crit...
13,735
Given the following text description, write Python code to implement the functionality described below step by step Description: A simple example on how to use jQAssistant with Python Pandas I'm a huge fan of the software analysis framework jQAssistant (http Step1: Step 2 Step2: Step 3 Step3: Step 4 Step4: Step 5 ...
Python Code: import py2neo import pandas as pd Explanation: A simple example on how to use jQAssistant with Python Pandas I'm a huge fan of the software analysis framework jQAssistant (http://www.jqassistant.org). It's a great tool for scanning and validating various software artifacts (get a glimpse at https://buschma...
13,736
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean 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', 'niwa', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NIWA Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Timestepping Framework, Ad...
13,737
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'sandbox-3', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-3 Topic: Atmoschem Sub-Topics: Transport, Emiss...
13,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Decoding sensor space data with generalization across time and conditions This example runs the analysis described in Step1: We will train the classifier on all left visual vs auditory tri...
Python Code: # Authors: Jean-Remi King <jeanremi.king@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD-3-Clause import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Standar...
13,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing surrogate models Tim Head, July 2016. Step1: Bayesian optimization or sequential model-based optimization uses a surrogate model to model the expensive to evaluate function func. ...
Python Code: import numpy as np np.random.seed(123) %matplotlib inline import matplotlib.pyplot as plt plt.set_cmap("viridis") Explanation: Comparing surrogate models Tim Head, July 2016. End of explanation from skopt.benchmarks import branin as _branin def branin(x, noise_level=0.): return _branin(x) + noise_level...
13,740
Given the following text description, write Python code to implement the functionality described below step by step Description: travelTime Analysis Different analyses of data collected using https Step1: Load data Step2: Convert the unix timestamp to a datetime object Step3: Add a new column with the duration in h...
Python Code: %matplotlib inline import pandas as pd, matplotlib.pyplot as plt, matplotlib.dates as dates, math from datetime import datetime from utils import find_weeks, find_days # custom from pytz import timezone from detect_peaks import detect_peaks from ipywidgets import interact, interactive, fixed, interact_manu...
13,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Evolution of sequence, structure and dynamics with Evol and SignDy This tutorial has two parts, focusing on two related parts of ProDy for studying evolution Step1: We also configure ProDy ...
Python Code: from prody import * from pylab import * %matplotlib inline confProDy(auto_show=False) Explanation: Evolution of sequence, structure and dynamics with Evol and SignDy This tutorial has two parts, focusing on two related parts of ProDy for studying evolution: The sequence sub-package Evol is for fetching, p...
13,742
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: convert an BGR image to RGB image
Python Code:: import cv2 import numpy as np array_of_image = np.array(image) image_rgb = cv2.cvtColor(array_of_image, cv2.COLOR_BGR2RGB) cv2.imshow('image', image_rgb)
13,743
Given the following text description, write Python code to implement the functionality described below step by step Description: K-nearest neighbors Step1: Let's imagine we measure 2 quantities, $x_1$ and $x_2$ for some objects, and we know the classes that these objects belong to, e.g., "star", 0, or "galaxy", 1 (ma...
Python Code: import numpy as np import matplotlib.pyplot as plt plt.style.use('notebook.mplstyle') %matplotlib inline from scipy.stats import mode Explanation: K-nearest neighbors End of explanation a = np.random.multivariate_normal([1., 0.5], [[4., 0.], ...
13,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Text generation using an RNN <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Download the Shak...
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,745
Given the following text description, write Python code to implement the functionality described below step by step Description: What is NLP? NLP is a field of linguistics and machine learning focused on understanding everything related to human language. The aim of NLP tasks is not only to understand single words ind...
Python Code: from transformers import pipeline classifier = pipeline('sentiment-analysis') classifier("I've been waiting for a HuggingFace course my whole life.") ## passing multiple sentences classifier([ "I've been waiting for a HuggingFace course my whole life.", "I hate this so much!" ]) Explanation: What ...
13,746
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="#Instantiate-CPPN" data-toc-modified-id="Instantiate-CPPN-1"><span class="toc...
Python Code: import numpy as np import yaml import os import cv2 import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import animation from datetime import datetime from pathlib import Path plt.rcParams['animation.ffmpeg_path'] = str(Path.home() / "anaconda3/envs/image-processing/bi...
13,747
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 2 Step1: 1. Load trajectory Read the heat current from a simple column-formatted file. The desired columns are selected based on their header (e.g. with LAMMPS format). For other in...
Python Code: import numpy as np import scipy as sp import matplotlib.pyplot as plt try: import sportran as st except ImportError: from sys import path path.append('..') import sportran as st c = plt.rcParams['axes.prop_cycle'].by_key()['color'] %matplotlib notebook Explanation: Example 2: Cepstral Analy...
13,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Jupyter Notebooks on Navigating Complexity <img src="http Step1: Or how many unique words are there. Step2: Or something more complicated, such as defining how a graph is p...
Python Code: len("in all honesty, counting all the words in a sentence is best done in a computers mind. It doesn't mind counting at all".split()) Explanation: Introduction to Jupyter Notebooks on Navigating Complexity <img src="http://jupyter.org/assets/jupyterpreview.png" style="height: 300px; float: right;"> </img> ...
13,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Regression Simple Linear Regression Running a SLR in Python is fairly simple once you know how to use the relevant functions. What might be confusing is that there exist several packa...
Python Code: # Load relevant packages %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') plt.rcParams['font.size'] = 14 Explanation: Linear Regression Simple Linear Regression Running a SLR in Python is fairly simple ...
13,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Variable pitch solenoid model A.M.C. Dawes - 2015 A model to design a variable pitch solenoid and calculate the associated on-axis B-field. Step2: Parameters Step3: Design discussion and c...
Python Code: import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl mpl.rcParams['legend.fontsize'] = 10 from mpl_toolkits.mplot3d import Axes3D %matplotlib inline I = 10 #amps mu = 4*np.pi*1e-7 #This gives B in units of Tesla Explanation: Variable pitch solenoid model A.M.C. Dawes - 2015 A model t...
13,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Stats Quality for 2016 College Nationals As one of the biggest tournaments hosted by USAU, the Club Nationals is one of the few tournaments where player statistics are relatively reli...
Python Code: import usau.reports import usau.fantasy from IPython.display import display, HTML import pandas as pd pd.options.display.width = 200 pd.options.display.max_colwidth = 200 pd.options.display.max_columns = 200 def display_url_column(df): Helper for formatting url links df.url = df.url.apply(lambda url: "...
13,752
Given the following text description, write Python code to implement the functionality described below step by step Description: 下載 ETC M06A 資料 <a href="http Step1: 基本的資料 Step2: 反過來由檔名找日期,可以用 regexp 或者 datetime Step3: 抓所有的壓縮檔案 Step4: 將 .tar.gz 重新打包成 .tar.xz
Python Code: from urllib.request import urlopen, urlretrieve import tqdm Explanation: 下載 ETC M06A 資料 <a href="http://www.freeway.gov.tw/UserFiles/File/TIMCCC/TDCS%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8A(tanfb)v3.0-1.pdf">國道高速公路電子收費交通資料蒐集支援系統(Traffic Data Collection System,TDCS)使用手冊</a> End of explanation # 歷史資料網址 data_base...
13,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Test DFA-2-RegExp Step1: As this regular expression is nearly unreadable, The notebook Rewrite.ipynb contains the definition of the function simplify that can be used to simplify this expr...
Python Code: %run DFA-2-RegExp.ipynb %run FSM-2-Dot.ipynb delta = { (0, 'a'): 0, (0, 'b'): 1, (1, 'a'): 1 } A = {0, 1}, {'a', 'b'}, delta, 0, {1} g, _ = dfa2dot(A) g r = dfa_2_regexp(A) r Explanation: Test DFA-2-RegExp End of explanation %run Rewrite.ipynb s = simplify(r, Rules) s Explanatio...
13,754
Given the following text description, write Python code to implement the functionality described below step by step Description: <h3 STYLE="background Step1: <h3 STYLE="background Step2: <h3 STYLE="background Step3: <h4 style="border-bottom Step4: 上図のように、qualityが6未満のワインと6以上のワインは volatile acidity の分布が異なるように見えます。その差...
Python Code: # 数値計算やデータフレーム操作に関するライブラリをインポートする import numpy as np import pandas as pd import scipy as sp from scipy import stats # URL によるリソースへのアクセスを提供するライブラリをインポートする。 # import urllib # Python 2 の場合 import urllib.request # Python 3 の場合 # 図やグラフを図示するためのライブラリをインポートする。 %matplotlib inline import matplotlib.pyplot as plt # 機...
13,755
Given the following text description, write Python code to implement the functionality described below step by step Description: XGBoost模型调优 加载要用的库 Step1: 载入数据 上一个ipython notebook已经做了下面这些数据特征预处理 1. City因为类别太多丢掉 2. DOB生成Age字段,然后丢掉原字段 3. EMI_Loan_Submitted_Missing 为1(EMI_Loan_Submitted) 为0(EMI_Loan_Submitted缺省) EMI_Loa...
Python Code: import pandas as pd import numpy as np import xgboost as xgb from xgboost.sklearn import XGBClassifier from sklearn import cross_validation, metrics from sklearn.grid_search import GridSearchCV import matplotlib.pylab as plt %matplotlib inline from matplotlib.pylab import rcParams rcParams['figure.figsize'...
13,756
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
13,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatial Model fitting in GLS In this exercise we will fit a linear model using a Spatial structure as covariance matrix. We will use GLS to get better estimators. As always we will need to ...
Python Code: # Load Biospytial modules and etc. %matplotlib inline import sys sys.path.append('/apps') sys.path.append('..') sys.path.append('../spystats') import django django.setup() import pandas as pd import matplotlib.pyplot as plt import numpy as np ## Use the ggplot style plt.style.use('ggplot') import tools Exp...
13,758
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...
13,759
Given the following text description, write Python code to implement the functionality described below step by step Description: cs231n case study toy NN example http Step1: Training a softmax linear classifier Step2: Softmax loss using cross-entropy keepdims variable forces the matrix shape !! - else np.sum result...
Python Code: import numpy as np # for quick visualization in notebook import matplotlib.pyplot as plt %matplotlib inline N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N*K,D)) # data matrix (each row = single example) y = np.zeros(N*K, dtype='uint8') # class labels f...
13,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Transformation This exploratory analysis takes into account how long does it take to a given open case to be closed. Step1: Transforming Column Names Step2: Transforming Open and Clos...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import bokeh from bokeh.io import output_notebook output_notebook() import os DATA_STREETLIGHT_CASES_URL = 'https://data.sfgov.org/api/views/c53t-rr3f/rows.json?accessType=DOWNLOAD' DATA_STREETLI...
13,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of large set of Abl simulations on Folding@home (project 10468), one starting configuration May 1, 2015 This is some initial MSM building Abl simulations. Section 0 Step1: The time...
Python Code: #Import libraries import matplotlib.pyplot as plt import mdtraj as md import glob import numpy as np from msmbuilder.dataset import dataset %pylab inline #Import longest trajectory. t = md.load("run0-clone35.h5") Explanation: Analysis of large set of Abl simulations on Folding@home (project 10468), one sta...
13,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Recovering rotation periods in simulated LSST data Step1: Randomly select targets from a TRILEGAL output. Step2: Calculate periods from ages and colours for cool stars Step3: Draw from a ...
Python Code: import numpy as np import matplotlib.pyplot as plt from gatspy.periodic import LombScargle import sys %matplotlib inline from toy_simulator import simulate_LSST from trilegal_models import random_stars import simple_gyro as sg import pandas as pd Explanation: Recovering rotation periods in simulated LSST d...
13,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create dataframe Step2: Make plot
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np Explanation: Title: Scatterplot In MatPlotLib Slug: matplotlib_stacked_bar_plot Summary: Scatterplot In MatPlotLib Date: 2016-05-01 12:00 Category: Python Tags: Data Visualization Authors: Chris Albon Based on: Seb...
13,764
Given the following text description, write Python code to implement the functionality described. Description: Number of subarrays have bitwise OR >= K Function to return the count of required sub - arrays ; Traverse sub - array [ i . . j ] ; Driver code
Python Code: def countSubArrays(arr , n , K ) : count = 0 ; for i in range(n ) : for j in range(i , n ) : bitwise_or = 0 for k in range(i , j + 1 ) : bitwise_or = bitwise_or | arr[k ]  if(bitwise_or >= K ) : count += 1    return count  if __name__== "__main __": arr =[3 , 4 , 5 ] n = ...
13,765
Given the following text description, write Python code to implement the functionality described below step by step Description: DTOcean Electrical Sub-Systems Example Note, this example assumes the Electrical Sub-Systems Module has been installed Step1: Create the core, menus and pipeline tree The core object carrys...
Python Code: %matplotlib inline from IPython.display import display, HTML import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (14.0, 8.0) import numpy as np from dtocean_core import start_logging from dtocean_core.core import Core from dtocean_core.menu import ModuleMenu, ProjectMenu from dtocean_core.pipe...
13,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex AI Pipelines Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Install the latest GA version of google-cloud-pipeline-components library as well. ...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex AI Pipelines: AutoML image classification pipelines using google-cloud-pipeline-co...
13,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Data and Preprocessing Step1: factorplot and FacetGrid
Python Code: names = [ 'mpg' , 'cylinders' , 'displacement' , 'horsepower' , 'weight' , 'acceleration' , 'model_year' , 'origin' , 'car_name' ] # reading the file and assigning the header df = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/a...
13,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Question 1 Step1: On vérifie en utilisant sympy que le calcul est correct Step2: Question 2 Step3: On vérifie en utilisant sympy que ce calcul est correct Step4: Question 3 Step5: On vé...
Python Code: def somme(A, B): C = [] for i in range(4): Ai = A[i] Bi = B[i] row = [Ai[j]+Bi[j] for j in range(4)] C.append(row) return C X = [[56, 39, 3, 41], [23, 78, 11, 62], [61, 26, 65, 51], [80, 98, 9, 68]] Y = [[51, 52, 53, 15], [ 1, 71, 46, 31], ...
13,769
Given the following text description, write Python code to implement the functionality described below step by step Description: 1 Creating an instance of the solow.Model class In this notebook I will walk you through the creation of an instance of the solow.Model class. To create an instance of the solow.Model we mus...
Python Code: solow.Model.output? Explanation: 1 Creating an instance of the solow.Model class In this notebook I will walk you through the creation of an instance of the solow.Model class. To create an instance of the solow.Model we must define two primitives: an aggregate production function and a dictionary of model ...
13,770
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialize PySpark First, we use the findspark package to initialize PySpark. Step1: Hello, World! Loading data, mapping it and collecting the records into RAM... Step2: Creating Objects f...
Python Code: from pyspark.sql import SparkSession # Initialize PySpark with MongoDB support APP_NAME = "Introducing PySpark" spark = ( SparkSession.builder.appName(APP_NAME) # Load support for MongoDB and Elasticsearch .config("spark.jars.packages", "org.mongodb.spark:mongo-spark-connector_2.12:3.0.1,org.el...
13,771
Given the following text description, write Python code to implement the functionality described below step by step Description: SETI Test Set Classification Accuracy This notebook provides the code needed to calculate the performance of your signal classification models using the PREVIEW test set (see Step 1. Get Dat...
Python Code: from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split import numpy as np import sklearn import csv import operator class_list = ['brightpixel', 'narrowband', 'narrowbanddrd', 'noise', 'squarepulsednarrowband', 'squiggle', 'squigglesquarepulsednarrowband'] fi...
13,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Practice with galaxy photometry and shape measurement To accompany galaxy-measurement lecture from the LSSTC Data Science Fellowship Program, July 2020. All questions and corrections can be ...
Python Code: # Load the packages we will use import numpy as np import astropy.io.fits as pf import astropy.coordinates as co from matplotlib import pyplot as pl import scipy.fft as fft %matplotlib inline Explanation: Practice with galaxy photometry and shape measurement To accompany galaxy-measurement lecture from the...
13,773
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', 'pcmdi', 'sandbox-2', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: PCMDI Source ID: SANDBOX-2 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Ene...
13,774
Given the following text description, write Python code to implement the functionality described below step by step Description: Now create the DrawControl and add it to the Map using add_control. We also register a handler for draw events. This will fire when a drawn path is created, edited or deleted (there are the ...
Python Code: dc = DrawControl(marker={'shapeOptions': {'color': '#0000FF'}}, rectangle={'shapeOptions': {'color': '#0000FF'}}, circle={'shapeOptions': {'color': '#0000FF'}}, circlemarker={}, ) def handle_draw(self, action, geo_json): print(action) ...
13,775
Given the following text description, write Python code to implement the functionality described below step by step Description: (&#x1F4D7;) ipyrad Cookbook Step1: Connect to cluster The code can be easily parallelized across cores on your machine, or many nodes of an HPC cluster using the ipyparallel library (see ou...
Python Code: import ipyrad.analysis as ipa import ipyparallel as ipp import toytree import toyplot print ipa.__version__ print toyplot.__version__ print toytree.__version__ Explanation: (&#x1F4D7;) ipyrad Cookbook: abba-baba admixture tests The ipyrad.analysis Python module includes functions to calculate abba-baba adm...
13,776
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', 'niwa', 'sandbox-3', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: NIWA Source ID: SANDBOX-3 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energ...
13,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Installation instructions First, clone cmac2.0 into your own directory Step2: This will start a distributed cluster on the arm_high_mem queue. I have set it to have 6 adi_cmac2 proce...
Python Code: import subprocess import os import sys from dask_jobqueue import PBSCluster from distributed import Client, progress from datetime import datetime, timedelta from pkg_resources import load_entry_point from distributed import progress def exec_adi(info_dict): This function will call adi_cmac2 from ...
13,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix generation Init symbols for sympy Step1: Lame params Step2: Metric tensor ${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$ Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_...
Python Code: from sympy import * from geom_util import * from sympy.vector import CoordSys3D N = CoordSys3D('N') alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True) init_printing() %matplotlib inline %reload_ext autoreload %autoreload 2 %aimport geom_util Explanation: Matrix generati...
13,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook Step1: Download or use cached file oecd-canada.json. Caching file on disk permits to work off-line and to speed up the exploration of the data. Step2: Initialize JsonStatCollectio...
Python Code: # all import here from __future__ import print_function import os import pandas as ps # using panda to convert jsonstat dataset to pandas dataframe import jsonstat # import jsonstat.py package import matplotlib as plt # for plotting %matplotlib inline Explanation: Notebook: using jsonstat.py python l...
13,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples of plots and calculations using the tmm package Imports Step1: Set up Step2: Sample 1 Here's a thin non-absorbing layer, on top of a thick absorbing layer, with air on both sides....
Python Code: from __future__ import division, print_function, absolute_import from tmm import (coh_tmm, unpolarized_RT, ellips, position_resolved, find_in_structure_with_inf) from numpy import pi, linspace, inf, array from scipy.interpolate import interp1d import matplotlib.pyplot as plt %matplot...
13,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Our Mission Spam detection is one of the major applications of Machine Learning in the interwebs today. Pretty much all of the major email service providers have spam detection systems built...
Python Code: ''' Solution ''' import pandas as pd # Dataset from - https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection df = pd.read_table('smsspamcollection/SMSSpamCollection', sep='\t', header=None, names=['label', 'sms_message']) # Output printing out...
13,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Fractal Dimension and Lacunarity Much of the code/theory is from Step1: Generate Data Generate a random walk of length n in d dimensions and plot it if it is 1, 2, or 3 dimensional. Step2: ...
Python Code: import scipy.optimize from pandas import Series, DataFrame import statsmodels.formula.api as sm import numpy as np, scipy, scipy.stats import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D Explanation: Fractal Dimension and Lacunarity Much of the code/theory is from: http://connor-johnson...
13,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the dmdd tutorial! A python package that enables simple simulation and Bayesian posterior analysis of nuclear-recoil data from dark matter direct detection experiments for a wide...
Python Code: I. Nuclear-recoil rates ----- ______ `dmdd` has three modules that let you calculate differential rate $\frac{dR}{dE_R}$ and total rate $R(E_R)$ of nuclear-recoil events: I) `rate_UV`: rates for a variety of UV-complete theories (from Gresham & Zurek, 2014) II) `rate_genNR`: rates for all non-relativis...
13,784
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate test data for SASS implementation of the Gibson-Lanni PSF. This Python algorithm has been verified against the original MATLAB code from the paper Li, J., Xue, F., & Blu, T. (2017)....
Python Code: import sys %pylab inline import scipy.special from scipy.interpolate import interp1d from scipy.interpolate import RectBivariateSpline print('Python {}\n'.format(sys.version)) print('NumPy\t\t{}'.format(np.__version__)) print('matplotlib\t{}'.format(matplotlib.__version__)) print('SciPy\t\t{}'.format(scipy...
13,785
Given the following text description, write Python code to implement the functionality described below step by step Description: 观测者模式(Observer Pattern) 1 代码 在门面模式中,我们提到过火警报警器。在当时,我们关注的是通过封装减少代码重复。而今天,我们将从业务流程的实现角度,来再次实现该火警报警器。 Step1: 以上是门面模式中的三个传感器类的结构。仔细分析业务,报警器、洒水器、拨号器都是“观察”烟雾传感器的情况来做反应的。因而,他们三个都是观察者,而烟雾传感器则是被观察对象...
Python Code: class AlarmSensor: def run(self): print ("Alarm Ring...") class WaterSprinker: def run(self): print ("Spray Water...") class EmergencyDialer: def run(self): print ("Dial 119...") Explanation: 观测者模式(Observer Pattern) 1 代码 在门面模式中,我们提到过火警报警器。在当时,我们关注的是通过封装减少代码重复。而今天,我们将从业务流...
13,786
Given the following text description, write Python code to implement the functionality described below step by step Description: In this example, we'e going to actually run a short simulation with OpenMM saving the results to disk with MDTraj's HDF5 reporter Obviously, running this example calculation on your machine ...
Python Code: import os import mdtraj import mdtraj.reporters Explanation: In this example, we'e going to actually run a short simulation with OpenMM saving the results to disk with MDTraj's HDF5 reporter Obviously, running this example calculation on your machine requires having OpenMM installed. OpenMM can be download...
13,787
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Tutorial Step1: We will try summarizing a small toy example; later we will use a larger piece of text. In reality, the text is too small, but it suffices as an illustrative example. Ste...
Python Code: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim.summarization import summarize Explanation: <h1>Tutorial: automatic summarization using Gensim</h1> This module automatically summarizes the given text, by extracting one or more important...
13,788
Given the following text description, write Python code to implement the functionality described below step by step Description: Create Space from an already existing .json input file Step1: Probe group information and get particle index Step2: Extract positions etc from a group Step3: Calculate center of mass for ...
Python Code: jsoninput = mc.InputMap('../src/examples/minimal.json') space = mc.Space(jsoninput) print(space.info()) print 'system volume = ',space.geo.getVolume() Explanation: Create Space from an already existing .json input file: End of explanation groups = space.groupList() for group in groups: print group.name...
13,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Biosignals Processing in Python Welcome to the course for biosignals processing using NeuroKit and python. You'll find the necessary files to run this example in the examples section. Import...
Python Code: # Import packages import neurokit as nk import pandas as pd import numpy as np import matplotlib import seaborn as sns # Plotting preferences %matplotlib inline matplotlib.rcParams['figure.figsize'] = [14.0, 10.0] # Bigger figures sns.set_style("whitegrid") # White background sns.set_palette(sns.color_pa...
13,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy random snippets Most comments are taken from the Numpy documentation. Import directive Step1: Tool functions Step2: Discrete distributions Bernoulli distribution Step3: Binomial dis...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Numpy random snippets Most comments are taken from the Numpy documentation. Import directive End of explanation def plot(data, bins=30): plt.hist(data, bins) plt.show() Explanation: Tool functions End of explanation ...
13,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom training and online prediction <table align="left"> <td> <a href="https Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Install the pillow...
Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" ! pip ...
13,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Recurrent Neural Networks in Theano Credits Step1: We now define a class that uses scan to initialize an RNN and apply it to a sequence of data vectors. The constructor initializes the shar...
Python Code: %matplotlib inline from synthetic import mackey_glass import matplotlib.pyplot as plt import theano import theano.tensor as T import numpy floatX = theano.config.floatX Explanation: Recurrent Neural Networks in Theano Credits: Forked from summerschool2015 by mila-udem First, we import some dependencies: En...
13,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib This notebook is (will be) a small crash course on the functionality of the Matplotlib Python module for creating graphs (and embedding it in notebooks). It is of course no substi...
Python Code: %matplotlib inline Explanation: Matplotlib This notebook is (will be) a small crash course on the functionality of the Matplotlib Python module for creating graphs (and embedding it in notebooks). It is of course no substitute for the proper Matplotlib thorough documentation. Initialization We need to add ...
13,794
Given the following text description, write Python code to implement the functionality described below step by step Description: As always, we load things from files so we don't have to set them up again. Step1: The flux_pairs variable is a list of 2-tuples, where the first element is the state we're calculating the ...
Python Code: old = paths.Storage("mistis.nc", 'r') engine = old.engines[0] network = old.networks[0] states = set(network.initial_states + network.final_states) # must ensure that the diskcache is disabled in order to save, # otherwise it looks for things that aren't there! cvs = old.cvs[:] for cv in cvs: cv.disabl...
13,795
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: how to delete a particular row in dataframe using python
Python Code:: dataFrame = dataFrame.drop(columns)
13,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook demonstrates pymatgen's functionality in terms of creating and editing molecules, as well as its integration with OpenBabel. For the latter, please note that you w...
Python Code: from pymatgen import Molecule # Create a methane molecule. coords = [[0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], [1.026719, 0.000000, -0.363000], [-0.513360, -0.889165, -0.363000], [-0.513360, 0.889165, -0.363000]] mol = Molecule(["C", "H", "H", "...
13,797
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-9s', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-9S Topic: Aerosol Sub-Topics: Transport, Emiss...
13,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploration of a problem interpreting binary test results Copyright 2015 Allen Downey MIT License Step1: p is the prevalence of a condition s is the sensititivity of the test The false posi...
Python Code: from __future__ import print_function, division import thinkbayes2 from sympy import symbols Explanation: Exploration of a problem interpreting binary test results Copyright 2015 Allen Downey MIT License End of explanation p, q, s, t1, t2 = symbols('p q s t1 t2') Explanation: p is the prevalence of a condi...
13,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Récupération des données Ce notebook donne quelques exemples de codes qui permettent de récupérer les données utilisées par d'autres notebooks. Le module actuariat_python est implémenté avec...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') # le code qui suit n'est pas indispensable, il génère automatiquement un menu # dans le notebook from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Récupération des données Ce notebook donne quelques exempl...