Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
2,300
Given the following text description, write Python code to implement the functionality described below step by step Description: The Idea Behind Gradient Descent In calculus, the gradient is the vector of partial derivatives and it identifies the direction of inputs that increase the functions outputs most quickly. We...
Python Code: def difference_quotient(f, x, h): return (f(x + h) - f(x)) / h Explanation: The Idea Behind Gradient Descent In calculus, the gradient is the vector of partial derivatives and it identifies the direction of inputs that increase the functions outputs most quickly. We can use gradient descent to maximize...
2,301
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding exponential mass loss/growth You can always modify the mass of particles between calls to sim.integrate. However, if you want to apply the mass/loss growth every timestep within call...
Python Code: import rebound import reboundx import numpy as np M0 = 1. # initial mass of star def makesim(): sim = rebound.Simulation() sim.G = 4*np.pi**2 # use units of AU, yrs and solar masses sim.add(m=M0) sim.add(a=1.) sim.add(a=2.) sim.add(a=3.) sim.move_to_com() return sim %matplot...
2,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Machine Learning- Random Forest Contest entry by Priyanka Raghavan and Steve Hall This notebook demonstrates how to train a machine learning algorithm to predict ...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable from sklearn.ensemble import RandomForestClassifier from pandas import set_option set_option("display...
2,303
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', 'cmcc', 'cmcc-cm2-vhr4', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-VHR4 Topic: Land Sub-Topics: Soil, Snow, Vegetatio...
2,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Level 3 In diesem Level lernen wir neue Datentypen, wie list, tuple, dict, set und frozenset kennen und lernen über Objekte dieser Typen mittels einer for-Schleife zu iterieren. Wir werden d...
Python Code: leer = list() leer2 = [] Explanation: Level 3 In diesem Level lernen wir neue Datentypen, wie list, tuple, dict, set und frozenset kennen und lernen über Objekte dieser Typen mittels einer for-Schleife zu iterieren. Wir werden die Schlüsselwörter del und for kennenlernen und auch den Schlüsselwörtern in, b...
2,305
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b>Reshaping data</b></font></p> © 2016, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110;&#98;&#111;&#115;&#115;...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: <p><font size="6"><b>Reshaping data</b></font></p> © 2016, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110;&#98;&#111;&#115;&#115;&#99;&#104;&#1...
2,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Training Logistic Regression via Stochastic Gradient Ascent The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will Step1: Load...
Python Code: from __future__ import division import graphlab Explanation: Training Logistic Regression via Stochastic Gradient Ascent The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will: Extract features from Amazon product reviews. Convert an SFrame int...
2,307
Given the following text description, write Python code to implement the functionality described below step by step Description: Standar usage of TensoFlow with model class Tipically use 3 files Step2: model_mnist_cnn.py Step3: train.py
Python Code: #! /usr/bin/env python import tensorflow as tf # Access to the data def get_data(data_dir='/tmp/MNIST_data'): from tensorflow.examples.tutorials.mnist import input_data return input_data.read_data_sets(data_dir, one_hot=True) #Batch generator def batch_generator(mnist, batch_size=256, type='train')...
2,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification COMP4670/8600 - Introduction to Statistical Machine Learning - Tutorial 3 $\newcommand{\trace}[1]{\operatorname{tr}\left{#1\right}}$ $\newcommand{\Norm}[1]{\lVert#1\rVert}$ $\...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.optimize as opt from scipy.special import expit # The logistic sigmoid function %matplotlib inline Explanation: Classification COMP4670/8600 - Introduction to Statistical Machine Learning - Tutorial 3 $\newcommand{\trace}[...
2,309
Given the following text description, write Python code to implement the functionality described below step by step Description: XGBoost Cross Validation The Python wrap around XGBoots implements a scikit-learn interface and this interface, more or less, support the scikit-learn cross validation system. More, XGBoost ...
Python Code: %matplotlib inline from __future__ import print_function import os import os.path as osp import numpy as np import pysptools.ml as ml import pysptools.skl as skl from sklearn.model_selection import train_test_split home_path = os.environ['HOME'] source_path = osp.join(home_path, 'dev-data/CZ_hsdb') result_...
2,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Plan Some data Step1: $\Rightarrow$ various different price series Step2: $\Longrightarrow$ There was a stock split 7 Step3: Define new financial instruments What we have now prices of fi...
Python Code: aapl = data.DataReader('AAPL', 'yahoo', '2000-01-01') print(aapl.head()) Explanation: Plan Some data: look at some stock price series devise a model for stock price series: Geometric Brownian Motion (GBM) Example for a contingent claim: call option Pricing of a call option under the assumtpion of GBM Chall...
2,311
Given the following text description, write Python code to implement the functionality described below step by step Description: 原文地址:itchat+pillow实现微信好友头像爬取和拼接。原文github地址 Step1: =======注意======= 这里我用Python2.7,实际上代码在Python3.6,3.5运行一切正常。itchat更新后就没有再测试啦。 注意微信更新了反广告机制,注意不要一次性发太多东西,避免被微信封号。 =======注意======= 核心 itchat读取微...
Python Code: #我的Python版本是: import sys print(sys.version) print(sys.version_info) Explanation: 原文地址:itchat+pillow实现微信好友头像爬取和拼接。原文github地址 End of explanation import itchat itchat.auto_login() Explanation: =======注意======= 这里我用Python2.7,实际上代码在Python3.6,3.5运行一切正常。itchat更新后就没有再测试啦。 注意微信更新了反广告机制,注意不要一次性发太多东西,避免被微信封号。 =====...
2,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Worapol B. and hamuel.me reserved some right maybe hahaha for muic math club and muic student that want to use this as references Import as DF From the data seen below we will use "master" s...
Python Code: df = pd.read_csv('t2_2016.csv') df = df[df['Type'] == 'master'] df.head() #format [Day, start_time, end_time] def time_extract(s): s = str(s).strip().split(" "*16) def helper(s): try: temp = s.strip().split(" ")[1:] comb = temp[:2] + temp[3:] comb[0] = co...
2,313
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Introduction to SimpleITKv4 Registration - Continued</h1> ITK v4 Registration Components <img src="ITKv4RegistrationComponentsDiagram.svg" style="width Step3: Utility fun...
Python Code: import SimpleITK as sitk # Utility method that either downloads data from the network or # if already downloaded returns the file name for reading from disk (cached data). from downloaddata import fetch_data as fdata # Always write output to a separate directory, we don't want to pollute the source directo...
2,314
Given the following text description, write Python code to implement the functionality described below step by step Description: Variant calling with kevlar Step1: Generate a random genome Rather than generating a truly random genome, I wanted one that shared some compositional features with the human genome. I used ...
Python Code: from __future__ import print_function import subprocess import kevlar import random import sys def gen_muts(): locs = [random.randint(0, 2500000) for _ in range(10)] types = [random.choice(['snv', 'ins', 'del', 'inv']) for _ in range(10)] for l, t in zip(locs, types): if t == 'snv': ...
2,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Overview This is part three of the tutorial where you will learn how to run same code in Part One (with minor changes) in Google's new Vertex AI pipeline. Vertex Pipelines helps you...
Python Code: PATH=%env PATH %env PATH={PATH}:/home/jupyter/.local/bin # CHANGE the following settings BASE_IMAGE='gcr.io/your-image-name' #This is the image built from the Dockfile in the same folder REGION='vertex-ai-region' #For example, us-central1, note that Vertex AI endpoint deployment region must match MODEL_STO...
2,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook ...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy import ndimage from...
2,317
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', 'cams', 'cams-csm1-0', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: CAMS Source ID: CAMS-CSM1-0 Sub-Topics: Radiative Forcings. Properti...
2,318
Given the following text description, write Python code to implement the functionality described below step by step Description: A real-world case (Physics Step1: 1 - The raw data Since the asymptotic behaviour is important, we place the majority of points on the $x>2$ area. Note that the definition of the grid (i.e....
Python Code: # Some necessary imports. import dcgpy import pygmo as pg import numpy as np # Sympy is nice to have for basic symbolic manipulation. from sympy import init_printing from sympy.parsing.sympy_parser import * init_printing() # Fundamental for plotting. from matplotlib import pyplot as plt %matplotlib inline ...
2,319
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: This chapter introduces two related topics Step2: Each update uses the same likelihood, but th...
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) if not exists(...
2,320
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...
2,321
Given the following text description, write Python code to implement the functionality described below step by step Description: Rate distributions Step1: A function to simulate trajectories. Step2: Simulation of a large number of events Generate a large results table. Step3: In this case, the info we are intereste...
Python Code: import matplotlib as mpl import matplotlib.pyplot as plt import random import numpy as np import beadpy import pandas as pd import math %matplotlib inline Explanation: Rate distributions: Time vs distance-weighted End of explanation def trajectory_simulator(pre_duration = 250, #Mean event start time ...
2,322
Given the following text description, write Python code to implement the functionality described below step by step Description: 6 - GSTools With version 0.5 scikit-gstat offers an interface to the awesome gstools library. This way, you can use a Variogram estimated with scikit-gstat in gstools to perform random field...
Python Code: # import import skgstat as skg import gstools as gs import numpy as np import matplotlib.pyplot as plt import plotly.offline as pyo import warnings pyo.init_notebook_mode() warnings.filterwarnings('ignore') # use the example from gstools # generate a synthetic field with an exponential model x = np.random....
2,323
Given the following text description, write Python code to implement the functionality described below step by step Description: Explanation of observed subconvergence Subconvergence has been observed when MESing operators which multiplies with $\frac{1}{J}$. In these cases, the error is dominant in the first inner po...
Python Code: %matplotlib notebook from IPython.display import display from sympy import Function, S, Eq from sympy import symbols, init_printing, simplify, Limit from sympy import sin, cos, tanh, exp, pi, sqrt from boutdata.mms import x # Import common import os, sys # If we add to sys.path, then it must be an absolute...
2,324
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'thu', 'ciesm', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: THU Source ID: CIESM Topic: Atmos Sub-Topics: Dynamical Core, Radiation, Turbulenc...
2,325
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis on Movie Reviews Using Logistic Regression Model 0 - negative 1 - somewhat negative 2 - neutral 3 - somewhat positive 4 - positive Load Libraries Step1: Load & Read Datas...
Python Code: import nltk import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier Explanation: Sentiment Analysis on M...
2,326
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Creating a Clean Chart Begin by importing the packages we'll use. Step1: Data looks better naked What in the world does that mean? Slide and data presentation often refers back to Edward...
Python Code: import pandas as pd import matplotlib.pyplot as plt import pylab as pyl # This is an example of an iPython magic command. # If we don't use this, then we can't see our matplotlib plots in our notebook %matplotlib inline Explanation: 1. Creating a Clean Chart Begin by importing the packages we'll use. End o...
2,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('reviews.txt', 'r') as f: reviews = f.read() with open('labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment ana...
2,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression test suite Step1: IMF notes Step2: The total number of stars $N_{tot}$ is then Step3: With a yield ejected of $0.1 Msun$, the total amount ejected is Step4: compared to the si...
Python Code: #from imp import * #s=load_source('sygma','/home/nugrid/nugrid/SYGMA/SYGMA_online/SYGMA_dev/sygma.py') #%pylab nbagg import sys import sygma as s print s.__file__ reload(s) s.__file__ #import matplotlib #matplotlib.use('nbagg') import matplotlib.pyplot as plt #matplotlib.use('nbagg') import numpy as np fro...
2,329
Given the following text description, write Python code to implement the functionality described below step by step Description: Power Spectral Density Introduction Methods This notebook consists of two methods to carry Spectral Analysis. The first one is based on covariance called pcovar, which comes from Spectrum St...
Python Code: % matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np from scipy import signal import matplotlib.pyplot as plt from matplotlib import mlab from spectrum import pcovar from pylab import rcParams rcParams['figure.figsize'] = 15, 6 Explanation: Power Spectral Density Introdu...
2,330
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="#Compare-weighted-and-unweighted-mean-temperature" data-toc-modified-id="Comp...
Python Code: %matplotlib inline import cartopy.crs as ccrs import matplotlib.pyplot as plt import numpy as np import xarray as xr Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Compare-weighted-and-unweighted-mean-temperature" data-toc-modi...
2,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book...
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network...
2,332
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is adapted from Step1: Init SparkContext Step2: A simple parameter server can be implemented as a Python class in a few lines of code. EXERCISE Step3: A worker can be implem...
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import ray import time Explanation: This notebook is adapted from: https://github.com/ray-project/tutorial/tree/master/examples/sharded_parameter_server.ipynb Sharded Parameter Se...
2,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Lending Club Step1: Abstract Lending club offers an exciting alternative to the stock market by providing loans that others can invest in. They claim a 4% overall default rate and give a gr...
Python Code: %matplotlib inline import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns from sklearn import preprocessing from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.feature_selection import SelectKBest, mutual_info_classif f...
2,334
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="jumbotron text-left"><b> This tutorial describes how to use the SMT toolbox to do some Bayesian Optimization (EGO method) to solve unconstrained optimization problem <div> Rémy P...
Python Code: import numpy as np %matplotlib notebook import matplotlib.pyplot as plt plt.ion() def fun(point): return np.atleast_2d((point-3.5)*np.sin((point-3.5)/(np.pi))) X_plot = np.atleast_2d(np.linspace(0, 25, 10000)).T Y_plot = fun(X_plot) lines = [] fig = plt.figure(figsize=[5,5]) ax = fig.add_subplot(111) ...
2,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step9: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be us...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson...
2,336
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power using DICS beamfomer Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ filter from single-trial activity to estimate source power across a frequency band. Refere...
Python Code: # Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # Roman Goj <roman.goj@gmail.com> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.time_frequency import csd_morlet from mne.beamformer import ma...
2,337
Given the following text description, write Python code to implement the functionality described below step by step Description: Sqlite3 and MySQL demo With the excellent ipython-sql jupyter extension installed, it becomes very easy to connect to SQL database backends. This notebook demonstrates how to do this. Note ...
Python Code: %load_ext sql Explanation: Sqlite3 and MySQL demo With the excellent ipython-sql jupyter extension installed, it becomes very easy to connect to SQL database backends. This notebook demonstrates how to do this. Note that this is a Python 2 notebook. First, we need to activate the extension: End of explana...
2,338
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: What is Biomedical Data Commons? Data Commons is an open knowledge graph of structured data. It contains statements about real world objects such as * The genome ass...
Python Code: # Install datacommons !pip install --upgrade --quiet datacommons Explanation: <a href="https://colab.research.google.com/github/datacommonsorg/api-python/blob/master/notebooks/analyzing_genomic_data.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Col...
2,339
Given the following text description, write Python code to implement the functionality described below step by step Description: HIV Methylation Age Advancement Step1: Run Age Predictions on HIV Dataset Step2: Hannum Model Step3: Preforming a linear adjustment on the control data. Step4: Horvath Model Step5: Qual...
Python Code: import NotebookImport from Setup.Imports import * from Setup.MethylationAgeModels import * from Setup.Read_HIV_Data import * hiv = (duration=='Control').map({False: 'HIV+', True: 'HIV-'}) hiv.name = 'HIV Status' hiv.value_counts() Explanation: HIV Methylation Age Advancement End of explanation def model_pl...
2,340
Given the following text description, write Python code to implement the functionality described below step by step Description: Applying Deterministic Methods Getting Started This tutorial focuses on using deterministic methods to square a triangle. Note that a lot of the examples shown here might not be applicable ...
Python Code: # Black linter, optional %load_ext lab_black import pandas as pd import numpy as np import chainladder as cl import matplotlib.pyplot as plt import os %matplotlib inline print("pandas: " + pd.__version__) print("numpy: " + np.__version__) print("chainladder: " + cl.__version__) Explanation: Applying Determ...
2,341
Given the following text description, write Python code to implement the functionality described below step by step Description: Kittens Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: If you have used the Internet, you have probably seen videos of kittens unrolling toilet paper. And you ...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
2,342
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
2,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: Units Each FloatParameter or FloatArrayParameter has an associated unit. Let's look at the 'sma' Parameter for the binary orbit. Step2: From the representation above, we ...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u,c logger = phoebe.logger(clevel='WARNING') b = phoebe.default_binary() Explanation: Advanced: Parameter Units In this tutorial we will learn about how units are handled in the frontend and how to translate between different units. Setup...
2,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Stochastic Differential Equations Step1: This background for these exercises is article of D Higham, An Algorithmic Introduction to Numerical Simulation of Stochastic Differential Equations...
Python Code: from IPython.core.display import HTML css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css' HTML(url=css_file) Explanation: Stochastic Differential Equations: Lab 2 End of explanation %matplotlib inline import numpy from matplotlib import pyplot fr...
2,345
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Persistent Homology of Sliding Windows Now that we have heuristically explored the geometry of sliding window embeddings of 1D signals, we will apply tools from persistent homology to...
Python Code: # Do all of the imports and setup inline plotting import numpy as np %matplotlib notebook import matplotlib.pyplot as plt from matplotlib import gridspec from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import PCA from scipy.interpolate import InterpolatedUnivariateSpline import ipywidget...
2,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Работа 1.4. Исследование вынужденной прецессии гироскопа Цель работы Step1: Параметры установки $f = 440$ Гц - резонансная частота. $l = 12,1$ см - расстояние до крайней риски. $T_{э} = 9 $...
Python Code: import numpy as np import scipy as ps import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Работа 1.4. Исследование вынужденной прецессии гироскопа Цель работы: исследовать вынужденную прецессию уравновешенного симметричного гироскопа; установить зависимость угловой скорости ...
2,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic regression with pyspark Import data Step1: Process categorical columns The following code does three things with pipeline Step2: Build StringIndexer stages Step3: Build OneHotEnc...
Python Code: cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True) cuse.show(5) Explanation: Logistic regression with pyspark Import data End of explanation from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler from pyspark.ml import Pipeline # categorical columns categoric...
2,348
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 ...
2,349
Given the following text description, write Python code to implement the functionality described below step by step Description: Lists Lists are collections of heterogeneous objects, which can be of any type, including other lists. Lists in the Python are mutable and can be changed at any time. Lists can be sliced ​​i...
Python Code: fruits = ['Apple', 'Mango', 'Grapes', 'Jackfruit', 'Apple', 'Banana', 'Grapes', [1, "Orange"]] # processing the entire list for fruit in fruits: print(fruit, end=", ") # print("*"*30) fruits.insert(0, "kiwi") print( fruits) # help(fruits.insert) # Including ft1 = list(fruits) print(id(ft1)...
2,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Analysis with NLTK Author Step1: 1. Corpus acquisition. In these notebooks we will explore some tools for text analysis and two topic modeling algorithms available from Python toolboxe...
Python Code: %matplotlib inline # Required imports from wikitools import wiki from wikitools import category import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import numpy as np import matplotlib.pyplot as plt from test_helper import Test impor...
2,351
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ML101.3 Step1: We'll re-use some of our code from before to visualize the data and remind us what we're looking at Step2: Visualizing the Data A good first-step for many problems is to ...
Python Code: from sklearn.datasets import load_digits digits = load_digits() Explanation: 2A.ML101.3: Supervised Learning: Classification of Handwritten Digits In this section we'll apply scikit-learn to the classification of handwritten digits. This will go a bit beyond the iris classification we saw before: we'll di...
2,352
Given the following text description, write Python code to implement the functionality described below step by step Description: QuTiP Example Step1: Imports Step2: Plotting Support Step3: Settings Step4: Superoperator Representations and Plotting We start off by first demonstrating plotting of superoperators, as ...
Python Code: from __future__ import division, print_function Explanation: QuTiP Example: Superoperators, Pauli Basis and Channel Contraction Christopher Granade <br> Institute for Quantum Computing $\newcommand{\ket}[1]{\left|#1\right\rangle}$ $\newcommand{\bra}[1]{\left\langle#1\right|}$ $\newcommand{\cnot}{{\scriptst...
2,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal For background, see Mapping Census Data, including the scan of the 10-question form. Keep in mind what people were asked and the range of data available in the census. Using the censu...
Python Code: # YouTube video I made on how to use the American Factfinder site to look up addresses from IPython.display import YouTubeVideo YouTubeVideo('HeXcliUx96Y') # standard numpy, pandas, matplotlib imports import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame, Series, Index import pan...
2,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Datalab Tutorial In this tutorial, we'll do some exploratory data analysis in BigQuery using Datalab. Requirements If you haven't already, you may sign-up for the free GCP trial credit. Bef...
Python Code: %sql -d standard SELECT * FROM `nyc-tlc.yellow.trips` LIMIT 5 Explanation: Datalab Tutorial In this tutorial, we'll do some exploratory data analysis in BigQuery using Datalab. Requirements If you haven't already, you may sign-up for the free GCP trial credit. Before you begin, give this project any...
2,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Multivariable Regression Model of FBI Property Crime Statistics Using the FBI Step1: Perfect accuracy, as expected. However...... Predicting ALL property crimes is a more interesting questi...
Python Code: import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import linear_model # Suppress annoying harmless error. warnings.filterwarnings( action="ignore" ) data_path = "https://raw.githubusercontent.com/Thinkful-Ed/data-201-resources/mas...
2,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Define target events based on time lag, plot evoked response This script shows how to define higher order events based on time lag between reference and target events. For illustration, we w...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.event import define_target_events from mne.datasets import sample import matplotlib.pyplot as plt print(__doc__) data_path = sample.data_path() Explanation: Define target events based on ...
2,357
Given the following text description, write Python code to implement the functionality described below step by step Description: 1D Data Analysis, Histograms, Boxplots, and Violin Plots Unit 7, Lecture 2 Numerical Methods and Statistics Prof. Andrew White, 2/27/2020 Goals Be able to histogram 1D data Understand the d...
Python Code: %matplotlib inline import random import numpy as np import matplotlib.pyplot as plt from math import sqrt, pi import scipy import scipy.stats plt.style.use('seaborn-whitegrid') !pip install --user pydataset Explanation: 1D Data Analysis, Histograms, Boxplots, and Violin Plots Unit 7, Lecture 2 Numerical Me...
2,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Emission from the relativistic charged particles The SR (spontaneous radiation) module calculates the spectral-spatial distibution of electromagnetic emission priduced by the relativistic ch...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import sys,time import numpy as np from scipy.constants import c,hbar from scipy.interpolate import griddata from chimera.moduls.species import Specie from chimera.moduls.chimera_main import ChimeraRun from chimera.moduls.SR import SR from chimera.moduls i...
2,359
Given the following text description, write Python code to implement the functionality described below step by step Description: ImageNet with GoogLeNet Input GoogLeNet (the neural network structure which this notebook uses) was created to analyse 224x224 pictures from the ImageNet competition. Output This notebook cl...
Python Code: import theano import theano.tensor as T import lasagne from lasagne.utils import floatX import numpy as np import scipy import matplotlib.pyplot as plt %matplotlib inline import os import json import pickle Explanation: ImageNet with GoogLeNet Input GoogLeNet (the neural network structure which this notebo...
2,360
Given the following text description, write Python code to implement the functionality described below step by step Description: Isentropic Analysis The MetPy function mpcalc.isentropic_interpolation allows for isentropic analysis from model analysis data in isobaric coordinates. Step1: Getting the data In this examp...
Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import numpy as np import xarray as xr import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units Explanation: Isentropic ...
2,361
Given the following text description, write Python code to implement the functionality described below step by step Description: Scattering and SBG-FS file stream read notebook This notebook explores setting up tasks for scatter and SBG's file storage setup. This runs multiple samples in a scatter plus batch mode. Ste...
Python Code: import sevenbridges as sbg from sevenbridges.errors import SbgError from sevenbridges.http.error_handlers import * import re import datetime import binpacking print("SBG library imported.") print sbg.__version__ Explanation: Scattering and SBG-FS file stream read notebook This notebook explores setting up ...
2,362
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 7 Step1: Today's lab reviews Maximum Likelihood Estimation, and introduces interctive plotting in the jupyter notebook. Part 1 Step2: Question 2 Step3: Question 3 Step4: Question 4 S...
Python Code: # Run this cell to set up the notebook. import numpy as np import pandas as pd import seaborn as sns import scipy as sci import matplotlib %matplotlib inline import matplotlib.pyplot as plt from matplotlib import patches, cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits....
2,363
Given the following text description, write Python code to implement the functionality described below step by step Description: <CENTER> <header> <h1>Pandas Tutorial</h1> <h3>EuroScipy, Cambridge UK, August 27th, 2015</h3> <h2>Joris Van den Bossche</h2> <p></p> Source Step1: Let's start with a showca...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn pd.options.display.max_rows = 8 Explanation: <CENTER> <header> <h1>Pandas Tutorial</h1> <h3>EuroScipy, Cambridge UK, August 27th, 2015</h3> <h2>Joris Van den Bossche</h2> <p></p> Source:...
2,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch. 11 - Evaluating and deploying the model In chapter 10 we have learned a lot of new tricks and tools to build neural networks that can deal with stuructured data such as the bank marketin...
Python Code: import keras from keras.models import load_model model = load_model('./support_files/Ch11_model.h5') Explanation: Ch. 11 - Evaluating and deploying the model In chapter 10 we have learned a lot of new tricks and tools to build neural networks that can deal with stuructured data such as the bank marketing d...
2,365
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step1: Exploring the Fermi distribution In quantum statistics, the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from IPython.html.widgets import interact, interactive, fixed Explanation: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. End of...
2,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Activité - Faire danser PoppyTorso Première partie Step1: Ensuite, vous allez créer un objet s'appellant poppy et étant un robot de type PoppyTorso. Vous pouvez donner le nom que vous souh...
Python Code: from poppy.creatures import PoppyTorso Explanation: Activité - Faire danser PoppyTorso Première partie : en utilisant, le simulateur V-REP : Compétences visées par cette activité : Savoir utiliser des modules en y récupérant des classes. Instancier un objet à partir d'une classe. Utiliser une méthode et un...
2,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic notebook to look @ convergence of a 2D region in an FES. It will actually call sum hills with the stride you set in cell one , graph the FES and put the regions of convergence there St...
Python Code: import numpy as np import matplotlib.pyplot as plt import glob import os from matplotlib.patches import Rectangle # define all variables for convergence script # these will pass to the bash magic below used to call plumed sum_hills dir="MetaD_converge" #where the intermediate fes will be stored hills="oth...
2,368
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing C4.5 and ID3 Decision Tree Algorithms with NumPy We will apply these trees to the the UCI car evaluation dataset $^1$ $^1$ https Step1: The backbone of the decision tree algori...
Python Code: import numpy as np #you only need matplotlib if you want to create some plots of the data import matplotlib.pyplot as plt %matplotlib inline data_path = "/home/brb/repos/examples/decision trees/UCI_cars" data = np.genfromtxt(data_path, delimiter=",", dtype=str) labels = ["buying", "maint", "doors", "person...
2,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 03 1 Least Square Coefficient Estimate $$\hat{\beta_1}=\frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sum_{i=1}^{n}(x_i-\bar{x})^2}$$ $$\hat{\beta_0}=\bar{y}-\hat{\beta_1}\bar{x}$...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline def LSCE(x, y): beta_1 = np.sum((x - np.mean(x))*(y-np.mean(y))) / np.sum((x-np.mean(x))*(x-np.mean(x))) beta_0 = np.mean(y) - beta_1 * np.mean(x) return beta_0, beta_1 advertising = pd.read_csv('Advertisi...
2,370
Given the following text description, write Python code to implement the functionality described below step by step Description: Extras This covers additional useful material that we may or may not have time to go over in the course. Generators Consider the following code that computes the sum of squared numbers up to...
Python Code: def squared_numbers(n): return [x*x for x in range(n)] def sum_squares(n): return sum(squared_numbers(n+1)) sum_squares(20000000) Explanation: Extras This covers additional useful material that we may or may not have time to go over in the course. Generators Consider the following code that compute...
2,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Template for test Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation. Included is N Phosphorylation however no benchmarks are av...
Python Code: from pred import Predictor from pred import sequence_vector from pred import chemical_vector Explanation: Template for test End of explanation par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Train...
2,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Co-Occurring Tag Analysis Analysing how tags co-occur across various Parliamentary publications. The idea behind this is to see whether there are naturally occurring groupings of topic tags ...
Python Code: #Data files !ls ../data/dataexport Explanation: Co-Occurring Tag Analysis Analysing how tags co-occur across various Parliamentary publications. The idea behind this is to see whether there are naturally occurring groupings of topic tags by virtue of their co-occurence when used to tag different classes of...
2,373
Given the following text description, write Python code to implement the functionality described below step by step Description: More on data structures Iterable vs. Iterators Lists are examples of iterable data structures, which means that you can iterate over the actual objects in these data structures. Step1: gene...
Python Code: # iterating over a list by object x = ['bob', 'sue', 'mary'] for name in x: print(name.upper() + ' WAS HERE') # alternatively, you could iterate over position for i in range(len(x)): print(x[i].upper() + ' WAS HERE') dir(x) # ignore the __ methods for now Explanation: More on data structures Iter...
2,374
Given the following text description, write Python code to implement the functionality described below step by step Description: This is a Jupyter notebook for David Dobrinskiy's HSE Thesis How Venture Capital Affects Startups' Success Step1: Let us look at the dynamics of total US VC investment Step3: Deals and inv...
Python Code: # You should be running python3 import sys print(sys.version) import pandas as pd # http://pandas.pydata.org/ import numpy as np # http://numpy.org/ import statsmodels.api as sm # http://statsmodels.sourceforge.net/stable/index.html import statsmodels.formula.api as smf import statsmodels print("Pandas...
2,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Activate logging for Gensim, so we can see that everything is working correctly. Gensim will, for example, complain if no C compiler is installed to let you know that Word2Vec will be awfull...
Python Code: import re import nltk import os.path as path from random import shuffle from gensim.models import Word2Vec Explanation: Activate logging for Gensim, so we can see that everything is working correctly. Gensim will, for example, complain if no C compiler is installed to let you know that Word2Vec will be awf...
2,376
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 3 Imports Step2: Character counting and entropy Write a function char_probs that takes a string and computes the probabilities of each character in the string Step4: Th...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact Explanation: Algorithms Exercise 3 Imports End of explanation def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s...
2,377
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Modular neural nets In the previous exercise, we started to build modules/general layers for implementing large neural networks. In this exercise, we will expand on this by implementi...
Python Code: # As usual, a bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers import * %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image....
2,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Pima Indian Diabetes Prediction ### Update History 2021-04-15 Added bypass of imputation of Num of Pregnancies field, switched to using only transform for test data, and added code to load d...
Python Code: import pandas as pd # pandas is a dataframe library import matplotlib.pyplot as plt # matplotlib.pyplot plots data %matplotlib inline Explanation: Pima Indian Diabetes Prediction ### Update History 2021-04-15 Added bypass of imputation of Num of Pregnancies field, switched to using onl...
2,379
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: <a id='section1'></a> 1. Recap of the global energy budget Let's look again at the observations Step2: Let's now deal with the shortwave (solar) side of the energy budget. A...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture 2: The zero-dimensional energy balance model Warning: content out of date and not maintained You really should be looking at The ...
2,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial - Transformers An example of how to incorporate the transfomers library from HuggingFace with fastai Step1: In this tutorial, we will see how we can use the fastai library to fine-...
Python Code: #|all_slow Explanation: Tutorial - Transformers An example of how to incorporate the transfomers library from HuggingFace with fastai End of explanation from transformers import GPT2LMHeadModel, GPT2TokenizerFast Explanation: In this tutorial, we will see how we can use the fastai library to fine-tune a pr...
2,381
Given the following text description, write Python code to implement the functionality described below step by step Description: Kudryavtsev Model Link to this notebook Step1: Part 1 We will run the Kudryatsev model for conditions in Barrow, Alaska in a very cold year, 1964. The mean annaul temperature for 1964 was -...
Python Code: # Load standard Python modules import numpy as np import matplotlib.pyplot as plt # Load PyMT model(s) import pymt.models ku = pymt.models.Ku() Explanation: Kudryavtsev Model Link to this notebook: https://github.com/csdms/pymt/blob/master/docs/demos/ku.ipynb Install command: $ conda install notebook pymt_...
2,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Real-time music auto-tagging In this tutorial, we use Essentia's TensorFlow integration to perform auto-tagging in real-time. Additionally, this serves as an example of TensorFlow inference ...
Python Code: !pip -q install pysoundcard Explanation: Real-time music auto-tagging In this tutorial, we use Essentia's TensorFlow integration to perform auto-tagging in real-time. Additionally, this serves as an example of TensorFlow inference in streaming mode and can be easily adapted to work offline. Setup To instal...
2,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Probability, Statistics, and Machine Learning Step1: Conditional Expectation and Mean Square Error In this section, we work through a detailed example using conditional expectati...
Python Code: import numpy as np np.random.seed(12345) Explanation: Python for Probability, Statistics, and Machine Learning End of explanation import sympy as S from sympy.stats import density, E, Die x=Die('D1',6) # 1st six sided die y=Die('D2',6) # 2nd six sides die a=S.symbols('a') z = x+y # sum of...
2,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Fibonacci Stretch Step1: You can also jump to Part 6 for more audio examples. Part 1 - Representing rhythm as symbolic data 1.1 Rhythms as arrays The main musical element we're going to pla...
Python Code: import IPython.display as ipd ipd.Audio("../data/out_humannature_90s_stretched.mp3", rate=44100) Explanation: Fibonacci Stretch: An Exploration Through Code by David Su This notebook and its associated code are also available on GitHub. Contents Introduction A sneak peek at the final result Part 1 - Repres...
2,385
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Solution Notebook Problem Step1: Algorithm Step2: Unit Test
Python Code: def permutations(str1, str2): return sorted(str1) == sorted(str2) Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Solution Notebook Problem: Determine if a string is a permutation of another string Constraints Test Cases Algorithm: Co...
2,386
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Nest-Neighbors 1 Unsupervised Neast Neighbors It acts as a uniform unterface to three different nestest neighbors algorithms Step1: We can also use the KDTree and BallTree classes direct...
Python Code: from sklearn.neighbors import NearestNeighbors import numpy as np X = np.array([[-1,-1],[-2, -1],[1,1],[2,1],[3,2]]) nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X) distance, indices = nbrs.kneighbors(X) indices distance Explanation: K-Nest-Neighbors 1 Unsupervised Neast Neighbors It ...
2,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Recognize named entities on Twitter with LSTMs In this assignment, you will use a recurrent neural network to solve Named Entity Recognition (NER) problem. NER is a common task in natural la...
Python Code: import sys sys.path.append("..") from common.download_utils import download_week2_resources download_week2_resources() Explanation: Recognize named entities on Twitter with LSTMs In this assignment, you will use a recurrent neural network to solve Named Entity Recognition (NER) problem. NER is a common tas...
2,388
Given the following text description, write Python code to implement the functionality described below step by step Description: How to create Popups Step1: Simple popups You can define your popup at the feature creation, but you can also overwrite them afterwards Step2: Vega Popup You may know that it's possible to...
Python Code: import sys sys.path.insert(0,'..') import folium print (folium.__file__) print (folium.__version__) Explanation: How to create Popups End of explanation m = folium.Map([45,0], zoom_start=4) folium.Marker([45,-30], popup="inline implicit popup").add_to(m) folium.CircleMarker([45,-10], radius=1e5, popup=foli...
2,389
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm using tensorflow 2.10.0.
Problem: import tensorflow as tf seed_x = 10 ### return the tensor as variable 'result' def g(seed_x): tf.random.set_seed(seed_x) return tf.random.uniform(shape=(10,), minval=1, maxval=5, dtype=tf.int32) result = g(seed_x)
2,390
Given the following text description, write Python code to implement the functionality described below step by step Description: PanSTARRS - WISE crossmatch Step1: Load the data Load the catalogues Step2: Coordinates As we will use the coordinates to make a cross-match we to load them Step3: Compute the ML paramete...
Python Code: import numpy as np from astropy.table import Table from astropy import units as u from astropy.coordinates import SkyCoord import pickle from mltier1 import get_center, get_n_m, estimate_q_m, Field %pylab inline field = Field(170.0, 190.0, 45.5, 56.5) Explanation: PanSTARRS - WISE crossmatch: Pre-configure...
2,391
Given the following text description, write Python code to implement the functionality described below step by step Description: Display a map E. coli central carbon metabolism. Step1: Visualize reaction-centric and/or metabolite-centric data.
Python Code: escher.Builder('e_coli_core.Core metabolism').display_in_notebook() Explanation: Display a map E. coli central carbon metabolism. End of explanation escher.Builder('e_coli_core.Core metabolism', reaction_data={'PGK': 100}, metabolite_data={'ATP': 20}).display_in_notebook() Explanation: Visualize reaction-c...
2,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Pochodna (różniczkowanie numeryczne) Różnica dzielona w przód Rozwińmy funkcję $f(x)$ w otoczeniu $h$ punktu $x$ w szereg Taylora Step1: Numeryczne całkowanie Całka to pole, więc obliczmy j...
Python Code: import numpy as np x = np.linspace(0, 10, 10) f = np.sin(x) f1 = np.cos(x) df = f[1:] - f[:-1] dx = x[1:] - x[:-1] x2 = (x[1:] + x[:-1])/2 fp = df/dx fp.shape, x.shape %matplotlib inline import matplotlib.pyplot as plt plt.plot(x2, np.cos(x2), 'o-') plt.plot(x2, fp, 'ro-') Explanation: Pochodna (różniczkow...
2,393
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring Review Data let's look at some typical reviews, how many files there are, what the distributions of review lengths and hours played are, etc. Step1: Football Manager 2015 Stats St...
Python Code: import os import sys from json import loads from collections import Counter import numpy as np import pandas as pd # So, let's take a look at how many lines are in our reviews files # Note: I just started processing GTAV after ending all the other processes os.chdir('..') ! wc -l data/*.jsonlines Explanati...
2,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the OpenAQ API The openaq api is an easy-to-use wrapper built around the OpenAQ Api. Complete API documentation can be found on their website. There are no keys or rate limits (as of ...
Python Code: import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt import openaq import warnings warnings.simplefilter('ignore') %matplotlib inline # Set major seaborn asthetics sns.set("notebook", style='ticks', font_scale=1.0) # Increase the quality of inline plots mpl.rcP...
2,395
Given the following text description, write Python code to implement the functionality described below step by step Description: 练习 1:写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座!。 Step1: 练习 2:写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出...
Python Code: name = input('请输入你的姓名') print('你好',name) print('请输入出生的月份与日期') month = int(input('月份:')) date = int(input('日期:')) if month == 4: if date < 20: print(name, '你是白羊座') else: print(name,'你是非常有性格的金牛座') if month == 5: if date < 21: print(name, '你是非常有性格的金牛座') else: ...
2,396
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: I am really enjoying having this weather station. I say weather station, but it is just a raspberry pi with a pressure and temperature sensor attached to it. Computers are versatile,...
Python Code: # Tell matplotlib to plot in line %matplotlib inline # import pandas import pandas # seaborn magically adds a layer of goodness on top of Matplotlib # mostly this is just changing matplotlib defaults, but it does also # provide some higher level plotting methods. import seaborn # Tell seaborn to set things...
2,397
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: We'll then start with the bundle from the end of the emcee tutorial. If you're running this notebook locally, you will need to run that first to create the emcee_advanced_t...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u # units import numpy as np logger = phoebe.logger('error') Explanation: Advanced: Custom Cost Funtion (with emcee) IMPORTANT: this tutorial assumes basic knowledge (and uses a file resulting from) the emcee tutorial, although the custom...
2,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Scapy in 15 minutes (or longer) Guillaume Valadon & Pierre Lalet Scapy is a powerful Python-based interactive packet manipulation program and library. It can be used to forge or decode packe...
Python Code: send(IP(dst="1.2.3.4")/TCP(dport=502, options=[("MSS", 0)])) Explanation: Scapy in 15 minutes (or longer) Guillaume Valadon & Pierre Lalet Scapy is a powerful Python-based interactive packet manipulation program and library. It can be used to forge or decode packets for a wide number of protocols, send the...
2,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC. All Rights Reserved. Step1: RLDS Step2: Import Modules Step3: Load dataset We can load the human dataset from the Panda Pick Place Can task of the Robosuite col...
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...