Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
6,300
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The Cirq Developers Step1: Hidden linear function problem <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step6: In this notebook...
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...
6,301
Given the following text description, write Python code to implement the functionality described below step by step Description: A primer on numerical differentiation In order to numerically evaluate a derivative $y'(x)=dy/dx$ at point $x_0$, we approximate is by using finite differences Step1: Why is it that the seq...
Python Code: dx = 1. x = 1. while(dx > 1.e-10): dy = (x+dx)*(x+dx)-x*x d = dy / dx print("%6.0e %20.16f %20.16f" % (dx, d, d-2.)) dx = dx / 10. Explanation: A primer on numerical differentiation In order to numerically evaluate a derivative $y'(x)=dy/dx$ at point $x_0$, we approximate is by using f...
6,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading of Libraries and Classes. Step1: Create forward bond future PV (Exposure) time profile Setting up parameters Step2: Data input for the CouponBond portfolio The word portfolio is us...
Python Code: %matplotlib inline from datetime import date import time import pandas as pd import numpy as np pd.options.display.max_colwidth = 60 from Curves.Corporates.CorporateDailyVasicek import CorporateRates from Boostrappers.CDSBootstrapper.CDSVasicekBootstrapper import BootstrapperCDSLadder from MonteCarloSimula...
6,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Electron REST API This website provides an electron insert factor REST API. A demonstration of the use of this API is given below. The source code for this heroku app is available at https S...
Python Code: # Copyright (C) 2016 Simon Biggs # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # This program is d...
6,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading CTD data with PySeabird Author Step1: Let's first download an example file with some CTD data Step2: The profile dPIRX003.cnv.OK was loaded with the default rule cnv.yaml The heade...
Python Code: %matplotlib inline from seabird.cnv import fCNV Explanation: Reading CTD data with PySeabird Author: Guilherme Castelão pySeabird is a package to parse/load CTD data files. It should be an easy task but the problem is that the format have been changing along the time. Work with multiple ships/cruises data ...
6,305
Given the following text description, write Python code to implement the functionality described below step by step Description: Look up columns for all tracts/block groups from 2010 decimal census (bunched in groups of 20 due to api quatas) Step1: merge all dataframes to one based on pairs of tracts and block groups...
Python Code: census_20 = api.query_census_api('census',39, '061','*','*',['H0030001', 'H0030002', 'H0030003', 'H0040002', 'H0040004', 'H0050002', 'H0060002', 'H0060003', 'H0060004', 'H0060005', 'H0060006', 'H0060007', 'H0060008', 'H0100001', 'H0130002', 'H0130003', 'H0130004', 'H0130005', 'H0130006', 'H0130007'], 2010,...
6,306
Given the following text description, write Python code to implement the functionality described below step by step Description: \d - 숫자 \s - 공백(whitespace) \w - 문자+숫자(alphanumeric) \t - tab \n - 개행문자 Step1: 인터넷 DB 읽기 Yahoo! Finance Google Finance St.Louis FED (FRED) Kenneth French's data library World Bank Google An...
Python Code: # 특정값 NA로 취급 na_val = {'term' : [36]} pd.read_csv('example_df.csv', na_values=na_val).head() # 행 생략 df.head() pd.read_csv('example_df.csv', skiprows=[1, 2]).head() # 일부 행만 읽기 df_output = pd.read_csv('example_df.csv', nrows=3) df_output # file output df_output.to_csv('df_output.csv', index=False, header=Fal...
6,307
Given the following text description, write Python code to implement the functionality described below step by step Description: Conjugate Priors Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: In the previous chapters we have used grid approximations to solve a variety of problems. One of m...
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(...
6,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: On-Device Training with TensorFlow Lite <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Not...
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...
6,309
Given the following text description, write Python code to implement the functionality described below step by step Description: 用 NumPy 就能辨識數字 Step1: 先下載 MNIST 資料 Step2: Q 先看看這些資料是什麼吧! Step3: Supervised Learning <img src="supervised.svg" /> 類比: <img src="supervised2.svg" /> 類比: 中文房間 Step4: 看一下 MNIST 的 y 是什麼 Step5...
Python Code: from PIL import Image import numpy as np Explanation: 用 NumPy 就能辨識數字 End of explanation import os import urllib from urllib.request import urlretrieve dataset = 'mnist.pkl.gz' def reporthook(a,b,c): print("\rdownloading: %5.1f%%"%(a*b*100.0/c), end="") if not os.path.isfile(dataset): origi...
6,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Nyquist Step1: Proportional control of the normalized DC-motor Zero-order hold sampling of the DC motor with transfer function $G(s)=\frac{1}{s(s+1)}$ gives the discrete time system \begin{...
Python Code: import numpy as np import sympy as sy import itertools import matplotlib.pyplot as plt import control.matlab as cm init_printing() %matplotlib inline Explanation: Nyquist End of explanation z,h = sy.symbols('z,h') eh = sy.exp(-h) H = ( (h-1+eh)*z + (1-eh-h*eh) )/( z*z - (1+eh)*z + 0.5) B,A = sy.fraction(H)...
6,311
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 import math as m 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 follo...
6,312
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Intro to Sparse Data and Embeddings Learning Objectives Step3: Building a Sentiment Analysis Model Let's train a sentiment-analysis model on this data that predicts i...
Python Code: # 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 # distribute...
6,313
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have the following datatype:
Problem: import pandas as pd id=["Train A","Train A","Train A","Train B","Train B","Train B"] arrival_time = ["0"," 2016-05-19 13:50:00","2016-05-19 21:25:00","0","2016-05-24 18:30:00","2016-05-26 12:15:00"] departure_time = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00","2016-05-24 12:50:00","2016-...
6,314
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- -*- coding Step1: By definition, a Graph is a collection of nodes (vertices) along with identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can be any hashable ob...
Python Code: import networkx as nx G = nx.Graph() G Explanation: <!-- -*- coding: utf-8 -*- --> Tutorial This guide can help you start working with NetworkX. Creating a graph Create an empty graph with no nodes and no edges. End of explanation G.add_node(1) Explanation: By definition, a Graph is a collection of nodes (...
6,315
Given the following text description, write Python code to implement the functionality described below step by step Description: <img align="right" src="../img/exercise_turning.png" /> Exercise Step1: 3. Motion code In the following program template, you must fill the gaps with the appropriate code. The idea is to co...
Python Code: import packages.initialization import pioneer3dx as p3dx p3dx.init() Explanation: <img align="right" src="../img/exercise_turning.png" /> Exercise: Turn the robot for an angle. You are going to make a program for turning the robot from the initial position at the start of the simulation, in the center of t...
6,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started with model selection Those who have used Scikit-Learn before will no doubt already be familiar with the Choosing the Right Estimator flow chart. This diagram is handy for tho...
Python Code: from __future__ import print_function import os import numpy as np import pandas as pd from sklearn.preprocessing import scale from sklearn.preprocessing import normalize from sklearn import cross_validation as cv from sklearn.metrics import confusion_matrix, classification_report from sklearn.metrics impo...
6,317
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'> </a> Step1: Fraction correctly identified Table of contents Define analysis free parameters Data preprocessing Fitting random forest Fraction correctly identified Spectrum Unfo...
Python Code: %load_ext watermark %watermark -a 'Author: James Bourbeau' -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend Explanation: <a id='top'> </a> End of explanation from __future__ import division, print_function from collections import defaultdict import itertools import numpy as np from scipy import in...
6,318
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 4 Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to Preview the Grading for each step ...
Python Code: import pandas as pd import numpy as np data_url = "https://fred.stlouisfed.org/graph/fredgraph.csv?chart_type=line&recession_bars=on&log_scales=&bgcolor=%23e1e9f0&graph_bgcolor=%23ffffff&fo=Open+Sans&ts=12&tts=12&txtcolor=%23444444&show_legend=yes&show_axis_titles=yes&drp=0&cosd=2015-12-26&coed=2017-01-30&...
6,319
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id="navigation"></a> Single-cell Hi-C data analysis Welcome to the second part of our analysis. Here we will work specifically with single-cell data. The outline Step1: In this case, we...
Python Code: import os from hiclib import mapping from mirnylib import h5dict, genome bowtie_path = '/opt/conda/bin/bowtie2' enzyme = 'DpnII' bowtie_index_path = '/home/jovyan/GENOMES/HG19_IND/hg19_chr1' fasta_path = '/home/jovyan/GENOMES/HG19_FASTA/' chrms = ['1'] genome_db = genome.Genome(...
6,320
Given the following text description, write Python code to implement the functionality described below step by step Description: Collaborative Filtering Step1: Finding Similar Users Euclidean Distance Score One very simple way to calculate a similarity score is to use a Euclidean distance score, which takes the items...
Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt # A dictionary of movie critics and their ratings of a small # set of movies critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree'...
6,321
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b>CASE - Bacterial resistance experiment</b></font></p> © 2021, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110...
Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt Explanation: <p><font size="6"><b>CASE - Bacterial resistance experiment</b></font></p> © 2021, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110;&#98;&#111;&#115;&#115;&#99;&...
6,322
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 3 Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers...
Python Code: import graphlab Explanation: Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function t...
6,323
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--NAVIGATION--> < Setting Up | Contents | Rates Information > Understanding the Documentations In order to make use of the API effective, we need to understand the input parameters and the...
Python Code: import oandapyV20 from oandapyV20 import API import oandapyV20.endpoints.pricing as pricing Explanation: <!--NAVIGATION--> < Setting Up | Contents | Rates Information > Understanding the Documentations In order to make use of the API effective, we need to understand the input parameters and the correspondi...
6,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate a left cerebellum volume source space Generate a volume source space of the left cerebellum and plot its vertices relative to the left cortical surface source space and the freesurf...
Python Code: # Author: Alan Leggitt <alan.leggitt@ucsf.edu> # # License: BSD (3-clause) import mne from mne import setup_source_space, setup_volume_source_space from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' subject = 'sample' aseg_fname = subjects_d...
6,325
Given the following text description, write Python code to implement the functionality described below step by step Description: The previous Notebook in this series used multi-group mode to perform a calculation with previously defined cross sections. However, in many circumstances the multi-group data is not given ...
Python Code: import matplotlib.pyplot as plt import numpy as np import os import openmc %matplotlib inline Explanation: The previous Notebook in this series used multi-group mode to perform a calculation with previously defined cross sections. However, in many circumstances the multi-group data is not given and one mu...
6,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Preconfigured Energy Balance Models In this document the basic use of climlab's preconfigured EBM class is shown. Contents are how to setup an EBM model show and access subprocesses integra...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab from climlab import constants as const Explanation: Preconfigured Energy Balance Models In this document the basic use of climlab's preconfigured EBM class is shown. Contents are how to setup an EBM model show and access ...
6,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Integrate Ray AIR with Feast feature store Step1: In this example, we showcase how to use Ray AIR with Feast feature store, leveraging both historical features for training a model and onli...
Python Code: # !pip install feast==0.20.1 ray[air]>=1.13 xgboost_ray Explanation: Integrate Ray AIR with Feast feature store End of explanation import os WORKING_DIR = os.path.expanduser("~/ray-air-feast-example/") %env WORKING_DIR=$WORKING_DIR ! mkdir -p $WORKING_DIR ! wget --no-check-certificate https://github.com/ra...
6,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Appendix B Step1: Combining cross_fields and best_fields Based on previous tuning, we have the following optimal parameters for each multi_match query type. Step2: We've seen the process t...
Python Code: %load_ext autoreload %autoreload 2 import importlib import os import sys from elasticsearch import Elasticsearch from skopt.plots import plot_objective # project library sys.path.insert(0, os.path.abspath('..')) import qopt importlib.reload(qopt) from qopt.notebooks import evaluate_mrr100_dev, optimize_que...
6,329
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Malo et al. 2014 Title Step1: Table 1 - Target Information for Ophiuchus Sources
Python Code: import warnings warnings.filterwarnings("ignore") from astropy.io import ascii import pandas as pd Explanation: ApJdataFrames Malo et al. 2014 Title: BANYAN. III. Radial velocity, Rotation and X-ray emission of low-mass star candidates in nearby young kinematic groups Authors: Malo L., Artigau E., Doyon R....
6,330
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Read Salaries.csv as a dataframe called sal. Step2: Check the head of the DataFrame. Step3: Use the .info() method to find out how many entries there are. Step4: Wha...
Python Code: import pandas as pd Explanation: <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a> SF Salaries Exercise - Solutions Welcome to a quick exercise for you to practice your pandas skills! We will be using the SF Salaries Dataset from Kaggle! Just follow along and complete the ...
6,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Responses for Chandra/HETG Let's see if we can figure out responses for the Chandra/HETG. This notebook will require sherpa, because we're using this for comparison purposes! Step1: Let's l...
Python Code: %matplotlib inline import matplotlib.pyplot as plt try: import seaborn as sns except ImportError: print("No seaborn installed. Oh well.") import numpy as np import pandas as pd import astropy.io.fits as fits import sherpa.astro.ui as ui import astropy.modeling.models as models from astropy.mo...
6,332
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', 'csir-csiro', 'vresm-1-0', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CSIR-CSIRO Source ID: VRESM-1-0 Topic: Aerosol Sub-Topics: Transpor...
6,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Piecewise exponential models and creating custom models This section will be easier if we recall our three mathematical "creatures" and the relationships between them. First is the survival ...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' from matplotlib import pyplot as plt import numpy as np import pandas as pd from lifelines.datasets import load_waltons waltons = load_waltons() T, E = waltons['T'], waltons['E'] from lifelines import ExponentialFitter fig, ax = plt.subplots...
6,334
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting sensor layouts of EEG Systems This example illustrates how to load all the EEG system montages shipped in MNE-python, and display it on fsaverage template. Step1: check all montage...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Joan Massich <mailsik@gmail.com> # # License: BSD Style. from mayavi import mlab import os.path as op import mne from mne.channels.montage import get_builtin_montages from mne.datasets import fetch_fsaverage from mne.viz import plot_ali...
6,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Install Misopy Step1: Restart the kernel (Kernel -> Restart), so that IPython finds Misopy Get Samtools Step2: The samtools binary should now be in bin/samtools Generate Indices of the bam...
Python Code: !pip install --user --quiet misopy Explanation: Install Misopy End of explanation from urllib import urlretrieve urlretrieve("http://depot.galaxyproject.org/package/linux/x86_64/samtools/samtools-0.1.19-Linux-x86_64.tgz","samtools.tgz") !tar -xf samtools.tgz Explanation: Restart the kernel (Kernel -> Resta...
6,336
Given the following text description, write Python code to implement the functionality described below step by step Description: seaborn.countplot Bar graphs are useful for displaying relationships between categorical data and at least one numerical variable. seaborn.countplot is a barplot where the dependent variable...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np plt.rcParams['figure.figsize'] = (20.0, 10.0) plt.rcParams['font.family'] = "serif" df = pd.read_csv('../../datasets/movie_metadata.csv') df.head() Explanation: seaborn.countplot Bar graphs are u...
6,337
Given the following text description, write Python code to implement the functionality described below step by step Description: Name Data preparation by using a template to submit a job to Cloud Dataflow Labels GCP, Cloud Dataflow, Kubeflow, Pipeline Summary A Kubeflow Pipeline component to prepare data by using a te...
Python Code: %%capture --no-stderr !pip3 install kfp --upgrade Explanation: Name Data preparation by using a template to submit a job to Cloud Dataflow Labels GCP, Cloud Dataflow, Kubeflow, Pipeline Summary A Kubeflow Pipeline component to prepare data by using a template to submit a job to Cloud Dataflow. Details Inte...
6,338
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Clustering Data Using K-Means
Python Code:: from sklearn.cluster import KMeans # Step 1: Initalise kmeans clustering model for 5 clusters and # fit on training data k_means = KMeans(n_clusters=5, random_state=101) k_means.fit(X_train) # Step 2: Predict cluster for training and test data and add results # as a column to the respect...
6,339
Given the following text description, write Python code to implement the functionality described below step by step Description: WT-Übung 2 - Aufgabe 7b Ein Schimpanse hat zwei Urnen vor sich Step1: Simulation Es werden $N$ zufällige Spiele durchgeführt und ausgewertet. Dabei werden die absoluten Häufigkeiten der (In...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from random import random, choice # Kugeln (Werte erstmal unwichtig) black, red, green, white = 0, 1, 2, 7 # Urnen kugeln_urne1 = [white, white, white, black, black] kugeln_urne2 = [white, green, green, red, red] # Wkeiten p_urne1 = 0.7 p_urne2 = 0.3 ...
6,340
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize channel over epochs as an image This will produce what is sometimes called an event related potential / field (ERP/ERF) image. 2 images are produced. One with a good channel and on...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation: Visualize channel over epochs as an...
6,341
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature Visualizer This notebook provides examples of visualizations done in other data studies and modifies them using the Yellowbrick library The first set of examples comes from the blog ...
Python Code: import os import sys # Modify the path sys.path.append("..") import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt g = yb.anscombe() Explanation: Feature Visualizer This notebook provides examples of visualizations done in other data studies and modifies them using the Yellowbrick...
6,342
Given the following text description, write Python code to implement the functionality described below step by step Description: ds1 Step1: <br> <br> <br> <br> Step2: Analyse versch. Datasets, Onset Frames, 441 Samples / Frame = 100 Hz format Step3: conclusions (dataset 2, 100 Hz frames)
Python Code: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # bound = int(len(X)*0.8) # X_train = X[:bound, :] # X_test = X[bound:, :] # y_train = y[:bound] # y_test = y[bound:] print(X_train.shape) print(y_train.shape) print(X_test.shape) print(y_test.shape) ss = StandardScal...
6,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Seismic acquisition fiddling The idea is to replicate what we've done so far but with 3 enhancements Step5: Survey object Step6: Perhaps s and r should be objects too. I think you might wa...
Python Code: import numpy as np import matplotlib.pyplot as plt from shapely.geometry import Point, LineString import geopandas as gpd import pandas as pd from fiona.crs import from_epsg %matplotlib inline Explanation: Seismic acquisition fiddling The idea is to replicate what we've done so far but with 3 enhancements:...
6,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Elemento LinearTriangle El elemento LinearTriangle es un elemento finito bidimensional con coordenadas locales y globales, caracterizado por una función de forma lineal. Puede ser utilizado ...
Python Code: %matplotlib inline from nusa import * Explanation: Elemento LinearTriangle El elemento LinearTriangle es un elemento finito bidimensional con coordenadas locales y globales, caracterizado por una función de forma lineal. Puede ser utilizado para problemas de esfuerzo y deformación plana. Este elemento tien...
6,345
Given the following text description, write Python code to implement the functionality described below step by step Description: Identifikation wertloser Codeteile im Projekt "Spring PetClinic" Auslastungsdaten vom Produktivbetrieb Datenquelle Step1: Berechnung wesentlicher Metriken für Größe und Nutzungsgrad Step2: ...
Python Code: import pandas as pd coverage = pd.read_csv("../dataset/jacoco_production_coverage_spring_petclinic.csv") coverage.head() Explanation: Identifikation wertloser Codeteile im Projekt "Spring PetClinic" Auslastungsdaten vom Produktivbetrieb Datenquelle: Gemessen wurde der Anwendungsbetrieb der Software über ei...
6,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Stochastic Gradient Descent l That is a simple yet very efficient approach to discriminative learning of linear classifiers under convex loss function such as(linear) Support Vector Machine ...
Python Code: from sklearn.linear_model import SGDClassifier X = [[0, 0], [1, 1]] y = [0, 1] clf = SGDClassifier(loss='hinge', penalty='l2') clf.fit(X, y) clf.predict([[2., 2.]]) clf.coef_ #To get the signed distance to the hyperplane clf.decision_function([[2., 2.]]) Explanation: Stochastic Gradient Descent l That is a...
6,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning Machines Taught by Patrick Hebron at NYU/ITP, Fall 2017 TensorFlow Basics Step1: Now let's try to do the same thing using TensorFlow Step2: Where's the resulting value? Notice tha...
Python Code: # Create input constants: X = 2.0 Y = 3.0 # Perform addition: Z = X + Y # Print output: print Z Explanation: Learning Machines Taught by Patrick Hebron at NYU/ITP, Fall 2017 TensorFlow Basics: "Graphs and Sessions" Let's look at a simple arithmetic procedure in pure Python: End of explanation # Import Tens...
6,348
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: 如何使用 DELF 和 TensorFlow Hub 匹配图像 <table class="tfo-notebook-buttons" align="...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
6,349
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling the Detectability of a Population of Transients A common LSST science case is to detect a large sample of some family of transient objects for further study. A good proxy for a sci...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import lsst.sims.maf.db as db import lsst.sims.maf.utils as utils import lsst.sims.maf.metrics as metrics import lsst.sims.maf.slicers as slicers import lsst.sims.maf.metricBundles as metricBundles from lsst.sims.utils import equatorialF...
6,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Last edit by David Lao - 2017/12/12 <br> <br> Netflix Analytics - Movie Recommendation through Correlations <br> I love Netflix! This project aims to build a movie recommendation mechanism w...
Python Code: import pandas as pd import numpy as np import math import re from scipy.sparse import csr_matrix import matplotlib.pyplot as plt import seaborn as sns from surprise import Reader, Dataset, SVD, evaluate sns.set_style("darkgrid") Explanation: Last edit by David Lao - 2017/12/12 <br> <br> Netflix Analytics -...
6,351
Given the following text description, write Python code to implement the functionality described below step by step Description: Ferrofluid - Part 2 Table of Contents Applying an external magnetic field Magnetization curve Remark Step1: and set up the simulation parameters where we introduce a new dimensionless param...
Python Code: import espressomd espressomd.assert_features('DIPOLES', 'LENNARD_JONES') from espressomd.magnetostatics import DipolarP3M from espressomd.magnetostatic_extensions import DLC import numpy as np Explanation: Ferrofluid - Part 2 Table of Contents Applying an external magnetic field Magnetization curve Remark:...
6,352
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/logo.jpg" style="display Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <span style="text-align Step5: <p style="text-align ...
Python Code: shoes_in_my_drawer = int(input("How many shoes do you have in your drawer? ")) if shoes_in_my_drawer % 2 == 1: print("You have an odd number of shoes. Something is wrong!") Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפי...
6,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Bad posterior geometry and how to deal with it HMC and its variant NUTS use gradient information to draw (approximate) samples from a posterior distribution. These gradients are computed in...
Python Code: !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro from functools import partial import numpy as np import jax.numpy as jnp from jax import random import numpyro import numpyro.distributions as dist from numpyro.diagnostics import summary from numpyro.infer import MCMC, NUTS assert numpyro.__v...
6,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot Emission Measure Distributions Compute and plot emission measure distributions, $\mathrm{EM}(T)$ for the EBTEL and HYDRAD results for varying pulse duration $\tau$. Step1: First, load ...
Python Code: import os import sys import pickle import numpy as np from scipy.optimize import curve_fit import seaborn.apionly as sns import matplotlib.pyplot as plt from matplotlib import ticker sys.path.append(os.path.join(os.environ['EXP_DIR'],'EBTEL_analysis/src')) import em_binner as emb %matplotlib inline plt.rcP...
6,355
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Step 1 Step2: <div class ="alert alert-success">As we can see in the above diagram, a lot of new relates to Politics and its related items. Also we can understand a t...
Python Code: ## required installation for LDA visualization !pip install pyLDAvis ## imports import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import LatentDirichletAllocation import m...
6,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Eaton & Ree (2013) single-end RAD data set Here we demonstrate a denovo assembly for an empirical RAD data set using the ipyrad Python API. This example was run on a workstation with 20 core...
Python Code: ## conda install ipyrad -c ipyrad ## conda install toytree -c eaton-lab ## conda install sra-tools -c bioconda ## imports import ipyrad as ip import ipyrad.analysis as ipa import ipyparallel as ipp Explanation: Eaton & Ree (2013) single-end RAD data set Here we demonstrate a denovo assembly for an empirica...
6,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Euler Step1: Below are the lists I created that will help me narrow my search. I created the list called search because the key was only allowed to contain 3 lower case letters. Nex...
Python Code: ciphertxt = open('cipher.txt', 'r') cipher = ciphertxt.read().split(',') #Splits the ciphertxt into a list, splits at every , cipher = [int(i) for i in cipher] ciphertxt.close() Explanation: Project Euler: Problem 59 https://projecteuler.net/problem=59 Each character on a computer is assigned a unique code...
6,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Nipype with Amazon Web Services (AWS) Several groups have been successfully using Nipype on AWS. This procedure involves setting a temporary cluster using StarCluster and potentially t...
Python Code: from nipype.interfaces.io import DataSink ds = DataSink() ds.inputs.base_directory = 's3://mybucket/path/to/output/dir' Explanation: Using Nipype with Amazon Web Services (AWS) Several groups have been successfully using Nipype on AWS. This procedure involves setting a temporary cluster using StarCluster a...
6,359
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate some validation videos random, download them from the server and then use them to visualize the results. Step1: Load the trained model with its weigths Step2: Extract the predicti...
Python Code: import random import os import numpy as np from work.dataset.activitynet import ActivityNetDataset dataset = ActivityNetDataset( videos_path='../dataset/videos.json', labels_path='../dataset/labels.txt' ) videos = dataset.get_subset_videos('validation') videos = random.sample(videos, 8) examples = ...
6,360
Given the following text description, write Python code to implement the functionality described below step by step Description: JVM Thread Dump Analysis Goal Step1: Get Data Dumps generated every 2 minutes and saved in one single file. Period Step2: Thread State by Date Problem Step3: Average of Threads by Hour Pr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np import pandas as pd plt.style.use('seaborn') from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture from mpl_toolkits.mplot3d import Axes3D import jvmthreadparser.pa...
6,361
Given the following text description, write Python code to implement the functionality described below step by step Description: 因为需要全市场回测所以本章无法使用沙盒数据,《量化交易之路》中的原始示例使用的是美股市场,这里的示例改为使用A股市场。 本节建议对照阅读abu量化文档第20-23节内容 本节的基础是在abu量化文档中第20节内容完成运行后有A股训练集交易和A股测试集交易数据之后 abu量化系统github地址 (您的star是我的动力!) abu量化文档教程ipython notebook 第...
Python Code: from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuFactorBuyBreak from abupy import abu, EMarketTargetType, AbuMetricsBase, ABuMarketDrawing, ABuProgress, ABuSymbolPd from abupy import EMarketTargetType, EDataCacheType, EMarketSourceType, EMarketDataFetchMode, EStoreAbu, ...
6,362
Given the following text description, write Python code to implement the functionality described below step by step Description: RNN Sentiment Classifier In the previous lab, you built a tweet sentiment classifier based on Bag-Of-Words features. Now we ask you to improve this model by representing it as a sequence of ...
Python Code: import tensorflow as tf import cPickle as pickle from collections import defaultdict import re, random import numpy as np from sklearn.feature_extraction.text import CountVectorizer #Read data and do preprocessing def read_data(fn): with open(fn) as f: data = pickle.load(f) #Clean the ...
6,363
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据清洗 删除空评论 删除评论中的空格,逗号,波浪线,换行 Step1: 用百度AI分析 ```python from aip import AipNlp https
Python Code: df1=data_train.drop(index=(data_train.loc[(data_train["评价内容"].isnull())].index)) df1["评价内容"]=df1["评价内容"].str.replace(" ","").str.replace(",","").str.replace("~","").str.replace("\n","") df1["分析"]=" " Explanation: 数据清洗 删除空评论 删除评论中的空格,逗号,波浪线,换行 End of explanation df1["prop"]="" df1["adj"]="" df1["sentiment"]...
6,364
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Preprocessing using Dataflow </h1> This notebook illustrates Step1: Kindly ignore the deprecation warnings and incompatibility errors related to google-cloud-storage. Step2: NOTE Step...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==1.25.0 Explanation: <h1> Preprocessing using Dataflow </h1> This notebook illustrates: <ol> <li> Creating datasets for Machine Learning using Dataflow </ol> <p> While Pandas is fine for experimenti...
6,365
Given the following text description, write Python code to implement the functionality described below step by step Description: Load data Predict the california average house value Step1: Model with the recommendation of the cheat-sheet - Based on the Sklearn algorithm cheat-sheet Step2: Improve the model parametri...
Python Code: from sklearn import datasets all_data = datasets.california_housing.fetch_california_housing() # Describe dataset print(all_data.DESCR) print(all_data.feature_names) # Print some data lines print(all_data.data[:10]) print(all_data.target) #Randomize, normalize and separate train & test from sklearn.utils i...
6,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Detached Binary Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Adding Datasets Now we'll create an empty mesh ...
Python Code: !pip install -I "phoebe>=2.1,<2.2" %matplotlib inline Explanation: Detached Binary: Roche vs Rotstar Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End ...
6,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
6,368
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color="red" size="6"><b>Programmation dynamique</b></font> <font color="blue" size="5"><b>I Fibonacci récursif naïf</b></font> Step1: Que constatez vous ??? Step2: hmmm.... pas fameu...
Python Code: # 1 1 2 3 5 8 13 21 39 ... # codez la fonction FiboRec (avec une fonction récursive) def FiboRec(n) : if n <=2 : return 1 return FiboRec(n-1)+FiboRec(n-2) for i in range(1,40) : print(i,FiboRec(i)) Explanation: <font color="red" size="6"><b>Programmation dynamique</b></font> <font color="blue" size...
6,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling data involves using observed datapoints to try to make a more general description of patterns that we see. It can be useful to describe the trajectory of a neuron's behavior in time...
Python Code: # Load data and pull out important values data = si.loadmat('../../data/StevensonV2.mat') # Only keep x, y dimensions, transpose to (trials, dims) hand_vel = data['handVel'][:2].T hand_pos = data['handPos'][:2].T # (neurons, trials) spikes = data['spikes'] # Remove all times where speeds are very slow thre...
6,370
Given the following text description, write Python code to implement the functionality described below step by step Description: Diffusion Monte Carlo propagators Most of the equations taken from Chapter 24 ("Projector quantum Monte Carlo") in "Interacting Electrons" (2016) by R.M. Martin, L. Reining, and D.M. Ceperle...
Python Code: T_op = Symbol('That') # Kinetic energy operator V_op = Symbol('Vhat') # Potential energy operator tau = Symbol('tau') # Projection time n = Symbol('n',isinteger=True) # Number of timestep divisions dt = Symbol(r'\Delta\tau') # Time for individual timestep # Eq. 24.7 Eq(exp(-tau *(T_op + V_op)), ...
6,371
Given the following text description, write Python code to implement the functionality described below step by step Description: SMA ROC Portfolio 1. The Security is above its 200-day moving average 2. The Security closes with sma_roc &gt; 0, buy. 3. If the Security closes with sma_roc &lt; 0, sell your long position....
Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf import strategy # Format price data. pd.options.display.float_format = '{:0.2f}'.format pd.set_option('display.max_rows', None) %matplotlib inline # Set size of inline plots '''note: rcParams can't be in same cell as ...
6,372
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: PCMDI Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Pr...
6,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex SDK Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the no...
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 SDK: AutoML training video classification model for batch prediction <table align=...
6,374
Given the following text description, write Python code to implement the functionality described below step by step Description: Natural Language Processing - Text Mining with Twitter API Introduction Using Natural Language Processing we can extract relevant and insightful data from social media. In this demonstration...
Python Code: #Import the necessary methods from tweepy library from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream access_token = "Access Token" access_token_secret = "Access Token Secret" consumer_key = "Consumer Key" consumer_secret = "Consumer Secret" class StdOutL...
6,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Analysis Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: This chapter presents a problem inspired by the game show The Price is Right. It is a silly examp...
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(...
6,376
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare photometry in the new Stripe82 catalog to Gaia DR2 photometry and derive corrections for gray systematics using Gmag photometry input Step1: <a id='dataReading'></a> Define paths a...
Python Code: %matplotlib inline from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astropy.table import hstack import matplotlib.pyplot as plt import numpy as np from astroML.plotting import hist # for astroML installation see https://www.astroml.org/user_guide...
6,377
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to Redis with Python In this notebook, we will go thourhg a similar set of commands as those described in the Redis Data Types introduction but using the redis-py Python clie...
Python Code: import redis Explanation: An Introduction to Redis with Python In this notebook, we will go thourhg a similar set of commands as those described in the Redis Data Types introduction but using the redis-py Python client from a Jupyter notebook. Remember that Redis is a server, and it can be access in a di...
6,378
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: So in numpy arrays there is the built in function for getting the diagonal indices, but I can't seem to figure out how to get the diagonal starting from the top right rather than to...
Problem: import numpy as np a = np.array([[ 0, 1, 2, 3, 4, 5], [ 5, 6, 7, 8, 9, 10], [10, 11, 12, 13, 14, 15], [15, 16, 17, 18, 19, 20], [20, 21, 22, 23, 24, 25]]) result = np.diag(np.fliplr(a))
6,379
Given the following text description, write Python code to implement the functionality described below step by step Description: Ejercicios 7 El Web Scraping (o Scraping) son un conjunto de técnicas que se utilizan para obtener de forma automática el contenido que hay en páginas web a través de su código HTML. Las té...
Python Code: import requests url = "https://es.wikipedia.org/wiki/Anexo:Municipios_de_la_Comunidad_de_Madrid" # Realizamos la petición HTTP a la web req = requests.get(url) # Comprobamos que la petición nos devuelve un Status Code = 200 statusCode = req.status_code if statusCode == 200: print('La petición ha ido bi...
6,380
Given the following text description, write Python code to implement the functionality described below step by step Description: 고유분해와 특이값 분해 정방 행렬 $A$에 대해 다음 식을 만족하는 단위 벡터 $v$, 스칼라 $\lambda$을 여러 개 찾을 수 있다. $$ Av = \lambda v $$ $ A \in \mathbf{R}^{M \times M} $ $ \lambda \in \mathbf{R} $ $ v \in \mathbf{R}^{M} $ 이러한 실...
Python Code: w, V = np.linalg.eig(np.array([[1, -2], [2, -3]])) w V Explanation: 고유분해와 특이값 분해 정방 행렬 $A$에 대해 다음 식을 만족하는 단위 벡터 $v$, 스칼라 $\lambda$을 여러 개 찾을 수 있다. $$ Av = \lambda v $$ $ A \in \mathbf{R}^{M \times M} $ $ \lambda \in \mathbf{R} $ $ v \in \mathbf{R}^{M} $ 이러한 실수 $\lambda$를 고유값(eigenvalue), 단위 벡터 $v$ 를 고유벡터(ei...
6,381
Given the following text description, write Python code to implement the functionality described below step by step Description: In this example, we use the Google geocoding API to translate addresses into geo-coordinates. Google imposes usages limits on the API. If you are using this script to index data, you many ne...
Python Code: from geopy.geocoders import GoogleV3 geolocator = GoogleV3() # geolocator = GoogleV3(api_key=<your_google_api_key>) Explanation: In this example, we use the Google geocoding API to translate addresses into geo-coordinates. Google imposes usages limits on the API. If you are using this script to index data,...
6,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Anomaly Detection in HTTP Logs This sample notebook demonstrates working with HTTP request logs data stored in BigQuery. Google Cloud Logging in the Google Cloud Platform makes it simple to ...
Python Code: from __future__ import division import google.datalab.bigquery as bq import matplotlib.pyplot as plot import numpy as np Explanation: Anomaly Detection in HTTP Logs This sample notebook demonstrates working with HTTP request logs data stored in BigQuery. Google Cloud Logging in the Google Cloud Platform ma...
6,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Source localization with equivalent current dipole (ECD) fit This shows how to fit a dipole Step1: Let's localize the N100m (using MEG only) Step2: Plot the result in 3D brain with the MR...
Python Code: from os import path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.forward import make_forward_dipole from mne.evoked import combine_evoked from mne.simulation import simulate_evoked from nilearn.plotting import plot_anat from nilearn.datasets import load_mni152_template data_...
6,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 1 Imports Step2: Euler's method Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation np.zeros? def solve_euler(derivs, y0, x): So...
6,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 1 Due Wednesday, September 2 by 2 Step1: Question 1 Pick a graph from Spurious Correlations and recreate it using matplotlib, numpy and pandas. For whichever graph you choose, save...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline Explanation: Homework 1 Due Wednesday, September 2 by 2:00 PM. Submit via email. Some helpful setup code. Feel free to add whatever else you might need. End of explanation # Code here Explanation: Question 1 Pick a gr...
6,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 22 Step1: By far, we'll use the plt object from the second import the most; that contains the main plotting library. Plotting in a script Let's say you're coding a standalone Python...
Python Code: import matplotlib as mpl import matplotlib.pyplot as plt Explanation: Lecture 22: Data Visualization CSCI 1360: Foundations for Informatics and Analytics Overview and Objectives Data visualization is one of, if not the, most important method of communicating data science results. It's analogous to writing:...
6,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: CheckpointerとPolicySaver <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: DQNエージェント 前のColabと同...
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...
6,388
Given the following text description, write Python code to implement the functionality described below step by step Description: Using GraphvizAnim to show how heapsort works Import the required packages and instantiate the animation Step1: Define an heap Step2: Now draw it (nodes will be named as the array indices ...
Python Code: from gvanim import Animation from gvanim.jupyter import interactive ga = Animation() Explanation: Using GraphvizAnim to show how heapsort works Import the required packages and instantiate the animation End of explanation heap = [ None, 5, 6, 7, 8, 9, 10, 11, 12 ] Explanation: Define an heap End of explana...
6,389
Given the following text description, write Python code to implement the functionality described. Description: Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1.
Python Code: def starts_one_ends(n): if n == 1: return 1 return 18 * (10 ** (n - 2))
6,390
Given the following text description, write Python code to implement the functionality described below step by step Description: Wind Structure Calculator This Python module provides a number of simple calculators with which the structure of line-driven winds can be determined following different analytic approaches. ...
Python Code: mstar = 52.5 # mass; if no astropy units are provided, the calculators will assume units of solar masses lstar = 1e6 # luminosity; if no astropy units are provided, the calculators will assume units of solar luminosities teff = 4.2e4 # effective temperature; if no astropy units are provided, the calcula...
6,391
Given the following text description, write Python code to implement the functionality described below step by step Description: PySAL Change Log Statistics This notebook pulls the summary statistics for use in the 6-month releases of PySAL, which is now (2017-07) a meta package. It assumes the subpackages have been ...
Python Code: from __future__ import print_function import os import json import re import sys import pandas from datetime import datetime, timedelta from time import sleep from subprocess import check_output try: from urllib import urlopen except: from urllib.request import urlopen import ssl import yaml contex...
6,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Things go wrong when programming all the time. Some of these "problems" are errors that stop the program from making sense. Others are problems that stop the program from working in s...
Python Code: from __future__ import division def divide(numerator, denominator): Divide two numbers. Parameters ---------- numerator: float numerator denominator: float denominator Returns ------- fraction: float numerator / denominato...
6,393
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: La senyal del so Si recordeu un exemple anterior, la funció sound ens retorna un valor entre 0 i 100, segons la intensitat del so. Anem a provar-la de nou, però repres...
Python Code: from functions import connect, sound, forward, stop connect() Explanation: <img src="http://cdn.shopify.com/s/files/1/0059/3932/products/Aldebaran_Robotics_Nao_Humanoid_Robot_07_d2010cf6-cff3-468b-82c4-e2c7cfa6df9b.jpg?v=1439318386" align="right" width=200> Sensor de so (micròfon) El micròfon del robot det...
6,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Document AI Form Parser (async) This notebook shows you how to analyze a set pdfs using the Google Cloud DocumentAI API asynchronously. Step1: Set your Processor Variables Step3: The follo...
Python Code: # Install necessary Python libraries and restart your kernel after. !pip install -r ../requirements.txt from google.cloud import documentai_v1beta3 as documentai from google.cloud import storage import os import re import pandas as pd Explanation: Document AI Form Parser (async) This notebook shows you how...
6,395
Given the following text description, write Python code to implement the functionality described below step by step Description: Previous 1.6 字典中的键映射多个值 问题 怎样实现一个键对应多个值的字典(也叫 multidict )? 解决方案 一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典: Step1: 选择使用列表还是集合取决于你的实际需求。如果你想保持元素的插入顺序...
Python Code: d = { "a" : [1, 2, 3], "b" : [4, 5] } e = { "a" : {1, 2, 3}, "b" : {4, 5} } Explanation: Previous 1.6 字典中的键映射多个值 问题 怎样实现一个键对应多个值的字典(也叫 multidict )? 解决方案 一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典: End of explanation from collections import defaultdic...
6,396
Given the following text description, write Python code to implement the functionality described below step by step Description: pyOpenCGA Basic User Usage [NOTE] The server methods used by pyopencga client are defined in the following swagger URL Step1: Now is time to import pyopencga modules. You have two options a...
Python Code: # Initialize PYTHONPATH for pyopencga import sys import os from pprint import pprint Explanation: pyOpenCGA Basic User Usage [NOTE] The server methods used by pyopencga client are defined in the following swagger URL: - http://bioinfo.hpc.cam.ac.uk/opencga-demo/webservices For tutorials and more info about...
6,397
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark Context Let's start with creating a SparkContext - an entry point to Spark application. Parameter 'local[*]' means that we create the Spark cluster locally using all machine cores. Nex...
Python Code: import pyspark sc = pyspark.SparkContext('local[*]') # do something to prove it works rdd = sc.parallelize(range(1000)) rdd.takeSample(False, 5) Explanation: Spark Context Let's start with creating a SparkContext - an entry point to Spark application. Parameter 'local[*]' means that we create the Spark clu...
6,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch normalization When changing the parameters of a model during the process of learning the distribition functions of each hidden layer are also changing. For that reason each layer needs...
Python Code: def batchnormalization(X, eps=1e-8, W=None, b=None): if X.get_shape().ndims == 4: mean = tf.reduce_mean(X, [0,1,2]) standar_desviation = tf.reduce_mean(tf.square(X-mean), [0,1,2]) X = (X - mean) / tf.sqrt(standar_desviation + eps) if W is not None and b is ...
6,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras for Text Classification Learning Objectives 1. Learn how to create a text classification datasets using BigQuery 1. Learn how to tokenize and integerize a corpus of text for training i...
Python Code: import os import pandas as pd from google.cloud import bigquery %load_ext google.cloud.bigquery Explanation: Keras for Text Classification Learning Objectives 1. Learn how to create a text classification datasets using BigQuery 1. Learn how to tokenize and integerize a corpus of text for training in Keras ...