Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
10,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color=red> 1 None订单 </font>
Step1: prior、train订单
Step2: 2 How many products do users buy each time
每张订单的商品数目
Step3: 3 Do users purchase different numbers of products each time?
用户每次... | Python Code:
order_is_None = order_products_train.groupby(['order_id'])['reordered'].sum().reset_index()
len(order_is_None[order_is_None.reordered == 0]) / len(order_is_None[order_is_None.reordered > 0])
a = pd.merge(order_is_None, orders, how = 'left', on = ['order_id'])
Explanation: <font color=red> 1 None订单 </font>
... |
10,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
O básico sobre tratamento de exceções
Erros detectados durante a execução são chamados de exceções e não são necessariamente fatais. A maioria das exceções não são lidadas pelos programas, e... | Python Code:
10 *(1/0)
4 + spam*3
'2' + 2
Explanation: O básico sobre tratamento de exceções
Erros detectados durante a execução são chamados de exceções e não são necessariamente fatais. A maioria das exceções não são lidadas pelos programas, entretanto, um resultado de mensagens de erros são ilustradas abaixo:
End of... |
10,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a simple launch. No reference to geo-position in control loop. Roll and yaw will be fixed at zero. Pitch will start at 90 deg until 60 m/s at which point we will pitch towards 30 deg... | Python Code:
linkup = krpc.connect('192.168.1.2', name='First Flight')
import numpy as np
from matplotlib import pyplot, cm
inf = np.inf
isclose = np.isclose
π = np.pi
arctan = np.arctan
sign = np.sign
class Controller(object):
'''Single Axis PID Controller'''
def __init__(self,set_point=0,limits=(-inf,inf),kp=... |
10,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Transformação-geométrica" data-toc-modified-id="Transformação-geométrica-1"><span class="toc-item-num">1 </span>Transform... | Python Code:
import numpy as np
t = np.array([2.1, 0.8])
T = np.array([[1,0,t[1]],
[0,1,t[0]],
[0,0,1]])
f = np.array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9,10],
[11,12,13,14,15]])
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Transformação-geo... |
10,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t... | Python Code:
# As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
fro... |
10,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
10,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lists, numpy arrays and all those confusing essential things that we do all the time
Package importing
Step1: Or you can also import a particular function or a subpackage from a package lik... | Python Code:
import numpy as np
np.random.random() #Random real number uniformly distributed between 0 and 1
np.random.normal() #Random real number following Gaussian distribution with mean=0 and standard deviation=1
Explanation: Lists, numpy arrays and all those confusing essential things that we do all the time
Pa... |
10,107 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have encountered a problem that, I want to get the intermediate result of a Pipeline instance in sklearn. | Problem:
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
from sklearn.pipeline import Pipeline
import pandas as pd
data = load_data()
pipe = Pipeline([
("tf_idf", TfidfVectorizer()),
("nmf", NMF())
])
pipe.fit_transform(data.test)
tf_idf_out =... |
10,108 | 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', 'ec-earth-consortium', 'ec-earth3-lr', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-LR
Topic: Land
Sub-T... |
10,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNNs tutorial
Step1: An LSTM/RNN overview
Step2: Note that when we create the builder, it adds the internal RNN parameters to the model.
We do not need to care about them, but they will be... | Python Code:
# we assume that we have the dynet module in your path.
# OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is.
from dynet import *
Explanation: RNNs tutorial
End of explanation
model = Model()
NUM_LAYERS=2
INPUT_DIM=50
HIDDEN_DIM=10
builder = LSTMBuilder(NUM_LAYERS... |
10,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parse angles
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demonstrates the function's flexibility
in handl... | Python Code:
import metpy.calc as mpcalc
Explanation: Parse angles
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demonstrates the function's flexibility
in handling various string formatting.
End of explanation
dir_str = 'SOUTH SOUTH EAS... |
10,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pyomo - Getting started
Pyomo installation
Step1: Ice cream example
This example is taken from the following book
Step3: Abstract Model
AbstHLinScript.py in https | Python Code:
from pyomo.environ import *
Explanation: Pyomo - Getting started
Pyomo installation: see http://www.pyomo.org/installation
pip install pyomo
End of explanation
instance = ConcreteModel(name="Linear (H)")
A = ['I_C_Scoops', 'Peanuts']
h = {'I_C_Scoops': 1, 'Peanuts': 0.1}
d = {'I_C_Scoops': 5, 'Peanut... |
10,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression Model
Dataset Information
No. of Features
Step1: Data Ingestion<a name='data ingestion'></a>
Step2: Features & Target Arrays<a name='features and target arrays'></a>
St... | Python Code:
%matplotlib inline
import os
import json
import time
import pickle
import requests
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import yellowbrick as yb
sns.set_palette('RdBu', 10)
Explanation: Logistic Regression Model
Dataset Information
No. of Features: 12... |
10,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Submission 4 from <a href="http
Step1: Load dataset
Step2: Utilities function
Step3: Extract data
Step4: Modified imputation method using MLPRegressor
Step5: Feature Augmentation method... | Python Code:
import numpy as np
np.random.seed(1337)
import warnings
warnings.filterwarnings("ignore")
import time as tm
import pandas as pd
from keras.models import Sequential, Model
from keras.constraints import maxnorm
from keras.layers import Dense, Dropout, Activation
from keras.utils import np_utils
from sklearn.... |
10,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Some notes about recent dolo development
Toolchain
build tool
Step1: Stateless / Statefree
Step2: two tools to improve the situation
Step3: Stateless approach in dolo
Step4: Towards more... | Python Code:
# numba-ification
from dolo.numeric.grids import UniformCartesianGrid, NonUniformCartesianGrid
grid = UniformCartesianGrid(min=[0.0, 0.0], max=[1.0, 1.0], n=[10, 10])
display(grid)
display(grid.__numba_repr__()) # fully type inferrable by numba / interpolation.py
import numba
numba.typeof(grid.__numba_re... |
10,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas Examples
Batfish questions can return a huge amount of data, which you may want to filter in various ways based on your task. While most Batfish questions support basic filtering, the... | Python Code:
# Import packages
%run startup.py
bf = Session(host="localhost")
# Initialize a network and a snapshot
bf.set_network("pandas-example")
SNAPSHOT_NAME = "snapshot"
SNAPSHOT_PATH = "networks/hybrid-cloud/"
bf.init_snapshot(SNAPSHOT_PATH, name=SNAPSHOT_NAME, overwrite=True)
Explanation: Pandas Examples
Batfis... |
10,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Breaking a variable to levels
The scenario for this tutorial is that, you have a series of a variable, such as the population density of different cities. And, you need to classify them into... | Python Code:
import geopandas as gpd # for reading and manupulating shapefile
import matplotlib.pyplot as plt # for making figure
import seaborn as sns # for making distplot
from colouringmap import theme_mapping as tm # a function named leveling_vector in tm will be used
from colouringmap import breaking_levels as bk ... |
10,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Horizon Graph
Originally called "two-tone pseudo-coloring", a horizon graph increases the density of time series graphs by dividing and layering filled line charts.
Intro
Step1: Visual at... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from bokeh.charts import Horizon, output_file, show
from bokeh.io import output_notebook
%matplotlib inline
output_notebook()
Explanation: Horizon Graph
Originally called "two-tone pseudo-coloring", a horizon grap... |
10,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 2
Step1: If we target a liquid system, we should not set up the particles in a lattice,
as this introduces unwanted structure in the starting configuration.
We define our system s... | Python Code:
from espressomd import System, electrostatics, electrostatic_extensions
from espressomd.shapes import Wall
import espressomd
import numpy
Explanation: Tutorial 2: A Simple Charged System, Part 2
7 2D Electrostatics and Constraints
In this section, we use the parametrized NaCl system from the last task to s... |
10,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DM_Halos and DM_IGM
Splitting $\langle DM_{cosmic}\rangle$ into its constituents.
Step1: $\langle \rho_{diffuse, cosmic}\rangle$
Use f_diffuse to calculate the average mass fraction of diff... | Python Code:
# imports
from importlib import reload
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline as IUS
from astropy import units as u
from frb.halos.models import ModifiedNFW
from frb.halos import models as frb_halos
from frb.halos import hmf as frb_hmf
from frb.dm import igm as frb_ig... |
10,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Impact on Initial Mass Function
When determining stellar masses in young stellar associations, non-magnetic models are often adopted. However, if magnetic inhibition of convection is an impo... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Impact on Initial Mass Function
When determining stellar masses in young stellar associations, non-magnetic models are often adopted. However, if magnetic inhibition of convection is an important process in governing the str... |
10,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Circles Metacog Analysis
Imports
Step1: Load Data
The metacog_dfs function creates 4 dataframes with metacognitive information
Step2: Sanity check
Let's see if the scale converge in order ... | Python Code:
%matplotlib inline
from __future__ import unicode_literals
import pandas as pd
import numpy as np
from glob import glob
from matplotlib import pyplot as plt
import seaborn as sns
from metacog_utils import add_sdt_utils, metacog_dfs, jointplot_group
from IPython.display import display
Explanation: Circles M... |
10,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating Geopackage Layers
Landung Setiawan 5/27/2016
Updated 6/29/2016
Note
Step1: Reading csv and printing as dictionary
Step2: Use shapely to make points
Since csv module doesn't distin... | Python Code:
%matplotlib inline
# Import the necessary libraries
import csv, os
from shapely.geometry import Point, mapping
import fiona, shapely
from fiona import Collection
import numpy as np
print "fiona version: {}".format(fiona.__version__)
print "shapely version: {}".format(shapely.__version__)
print "gdal versio... |
10,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Exploration
Research provides utility functions to query pricing, volume, and returns data for 8000+ US equities, from 2002 up to the most recently completed trading day. These function... | Python Code:
# Research environment functions
from quantopian.research import returns, symbols
# Select a time range to inspect
period_start = '2014-01-01'
period_end = '2017-1-1'
# Query returns data for AAPL
# over the selected time range
aapl_returns = returns(
assets=symbols('AAPL'),
start=period_start,
... |
10,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gippsland Basin Uncertainty Study
Step1: The Gippsland Basin Model
In this example we will apply the UncertaintyAnalysis class we have been playing with in the previous example to a 'realis... | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
#import the ususal libraries + the pynoddy UncertaintyAnalysis class
import sys, os
# determine path of repository to set paths corretly below
repo_path = os.path.realpath('/Users/flow/git/py... |
10,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create some text
Step2: Apply regex | Python Code:
# Load regex package
import re
Explanation: Title: Match URLs
Slug: match_urls
Summary: Match URLs
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon
Source: StackOverflow
Preliminaries
End of explanation
# Create a variable containing a text string
text = 'My blog is http://www.chr... |
10,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization 1
Step1: Scatter plots
Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot.
Generate random data using np.random.randn.
Style the markers (color, size... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Visualization 1: Matplotlib Basics Exercises
End of explanation
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x,y, s = 20, c = 'b')
plt.xlabel('Random Number 2')
plt.ylabel('Random Number')
plt.title('Random ... |
10,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Name
Data preparation using Hadoop MapReduce on YARN with Cloud Dataproc
Label
Cloud Dataproc, GCP, Cloud Storage, Hadoop, YARN, Apache, MapReduce
Summary
A Kubeflow Pipeline component to pr... | Python Code:
%%capture --no-stderr
KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz'
!pip3 install $KFP_PACKAGE --upgrade
Explanation: Name
Data preparation using Hadoop MapReduce on YARN with Cloud Dataproc
Label
Cloud Dataproc, GCP, Cloud Storage, Hadoop, YARN, Apache, MapReduce
Sum... |
10,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project 2
Step1: Now, can you find out the following facts about the dataset?
- Total number of students
- Number of students who passed
- Number of students who failed
- Graduation rate of... | Python Code:
# Import libraries
import numpy as np
import pandas as pd
# Read student data
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
# Note: The last column 'passed' is the target/label, all other are feature columns
student_data.head()
#student_data.describe()
student_data.... |
10,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programmatic Access to Genome Nexus
This notebook gives some examples in Python for programmatic access to http
Step1: Connect with cBioPortal API
cBioPortal also uses Swagger for their API... | Python Code:
from bravado.client import SwaggerClient
client = SwaggerClient.from_url('https://www.genomenexus.org/v2/api-docs',
config={"validate_requests":False,"validate_responses":False,"validate_swagger_spec":False})
print(client)
dir(client)
for a in dir(client):
client.__setat... |
10,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In a previous post, I introduced xarray with some simple manipulation and data plotting. In this super-short post, I'm going to do some more manipulation, using multiple input files to creat... | Python Code:
import xarray as xr
import os
import glob
Explanation: In a previous post, I introduced xarray with some simple manipulation and data plotting. In this super-short post, I'm going to do some more manipulation, using multiple input files to create a new dimension, reorganize the data and store them in multi... |
10,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
see
Step1: Some calendar information so we can support any netCDF calendar.
Step4: A few calendar functions to determine the number of days in each month
If you were just using the standa... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xarray
from netCDF4 import num2date
from netCDF4 import Dataset
# !conda list
print("numpy version :", np.__version__)
print("pandas version :", pd.__version__)
print("xray version :", xarray.__version__)
E... |
10,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decision Trees and Random Forests
Suppose you're classifying dogs, and you know (as an expert in the field) that all poodles have tails shorter than 15mm, while all dachshunds have tails lon... | Python Code:
def breed(tail, height):
if tail > 25:
if height < 35:
return 'dachshund'
else:
return 'golden retriever'
elif tail < 15:
return 'poodle'
else:
return 'dunno'
Explanation: Decision Trees and Random Forests
Suppose you're classifying dogs, ... |
10,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Evoked data structure
Step1: Creating Evoked objects from Epochs
Step2: Basic visualization of Evoked objects
We can visualize the average evoked response for left-auditory stimuli usi... | Python Code:
import os
import mne
Explanation: The Evoked data structure: evoked/averaged data
This tutorial covers the basics of creating and working with :term:evoked
data. It introduces the :class:~mne.Evoked data structure in detail,
including how to load, query, subselect, export, and plot data from an
:class:~mne... |
10,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Download the dataset
Fetch the Portuguese/E... | 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... |
10,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solutions to
Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1)
Welcome to the hands-on session of our tutorial! This tutorial is based on the user guide of NetworKi... | Python Code:
from networkit import *
Explanation: Solutions to
Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1)
Welcome to the hands-on session of our tutorial! This tutorial is based on the user guide of NetworKit, our network analysis software. You will learn in this tutorial how to use Net... |
10,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Working with xml
Step1: 1.3 From file to XML object
Opening an xml file is actually quite simple
Step2: As you can see, we obtained an instance of type lxml.etree._ElementTree. It mea... | Python Code:
from lxml import etree
Explanation: 1. Working with xml : reading
1.1 Introduction
Extensible Markup Language (XML) is a simple, very flexible text format derived from SGML (ISO 8879). Originally designed to meet the challenges of large-scale electronic publishing, XML is also playing an increasingly impor... |
10,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rand 2011 Cooperation Study
This notebook outlines how to recreate the analysis of the Rand et al. 2011 study "Dynamic social networks promote cooperation in experiments with humans" Link to... | Python Code:
from bedrock.client.client import BedrockAPI
Explanation: Rand 2011 Cooperation Study
This notebook outlines how to recreate the analysis of the Rand et al. 2011 study "Dynamic social networks promote cooperation in experiments with humans" Link to Paper
This outlines the steps to re-create the analysis us... |
10,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Support Vector Classifier
Support vector machines are a set of supervised learning algorithms that you can use for classification, regression and outlier detection purposes. SciKit-Le... | Python Code:
import pandas as pd
# The Dataset comes from:
# https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
# Load up the data.
with open('../Datasets/optdigits.tes', 'r') as f: testing = pd.read_csv(f)
with open('../Datasets/optdigits.tra', 'r') as f: training = pd.read_csv(f)
#... |
10,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2017 NCTU Data Maning HW0
0416037 李家安
Info
Group 3
Dataset
Step1: Connect sql
Step2: Remove NAN
觀察發現只有 birth 有出現 NAN,用 mean 取代沒有紀錄的 NaN
Step3: 避免出現 start time >= end time
Step4: 刪除 speed... | Python Code:
import pandas as pd
import datetime
df = pd.read_csv('201707-citibike-tripdata.csv')
df.columns = ['tripduration','starttime','stoptime',\
'start_station_id','start_station_name','start_station_latitude','start_station_longitude',\
'end_station_id','end_station_name','end_statio... |
10,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ránking de investigadores en Informática en la UGR
Step1: Los datos han sido descargados de la web de la UGR
usando urllib2
A continuación se muestra la tabla descargada
Step2: El siguient... | Python Code:
%matplotlib inline
from BeautifulSoup import BeautifulSoup
import urllib2
from IPython.display import (
display, HTML
)
import matplotlib.pyplot as plt
url = 'http://investigacion.ugr.es/ugrinvestiga/static/BuscadorRanking/*/buscar?tipo=&rama_c=&disciplina_c=TELE_D&especialidad_c=&indicador=&periodo=... |
10,141 | 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', 'cams', 'sandbox-1', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CAMS
Source ID: SANDBOX-1
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation,... |
10,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 33
Step1: import os and use unlink() to delete a file
Step2: os.rmdir() can delete folders, but only empty folders.
Step3: shutil hasa rmtree() function, which is the inverse of th... | Python Code:
import os
# Define base directory
defaultpath = os.path.expanduser('~/Dropbox/learn/books/Python/AutomateTheBoringStuffWithPython')
#Change directory to files directory if set in default
if (os.getcwd() == defaultpath):
os.chdir('/files')
else:
os.chdir(defaultpath + '/files')
Explanation: ... |
10,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logging 模块
data, object type
print to terminal
write to log.txt
different level?
Step1: Quick Start
导入模块后直接logging.waring(),logging.error()简单粗暴地调用即可。默认的level是DEBUG,所以warning会打印出信息,info级别更低,... | Python Code:
import logging
Explanation: Logging 模块
data, object type
print to terminal
write to log.txt
different level?
End of explanation
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import logging
logging.warning('Watch out!') # print message to console
logging.info('I told you so') # will not print anything
Ex... |
10,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Find Me
Michael duPont - CodeCamp 2017
Find Faces
The first thing we need to do is pick out faces from a larger image. Because the model for this is not user or case specific, we can ... | Python Code:
import cv2
import numpy as np
CASCADE = cv2.CascadeClassifier('findme/haar_cc_front_face.xml')
def find_faces(img: np.ndarray, sf=1.16, mn=5) -> np.array([[int]]):
Returns a list of bounding boxes for every face found in an image
return CASCADE.detectMultiScale(
cv2.cvtColor(img, cv2.COLOR_... |
10,145 | 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... |
10,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing and Breaking ConvNets
In this exercise we will visualize saliency maps for individual images and we will construct images to fool a trained ConvNet.
Step1: Load the data and pre... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from time import time
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# ... |
10,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Here we look at some Chang'e 5 high-speed data decoded by Paul Marsh M0EYT.
The frames are CCSDS concatenated frames with a Reed-solomon interleaving depth of 4. The frame size is 1024 bytes... | Python Code:
def load_frames(path):
frame_size = 1024
frames = np.fromfile(path, dtype = 'uint8')
frames = frames[:frames.size//frame_size*frame_size].reshape((-1, frame_size))
# drop ccsds header
frames = frames[:, 4:]
return frames
frames = np.concatenate([load_frames(f) for f in sorted(pathli... |
10,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GRIB Data Example
GRIB format is commonly used to disemminate atmospheric model data. With Xarray and the cfgrib engine, GRIB data can easily be analyzed and visualized.
Step1: To read GRIB... | Python Code:
import xarray as xr
import matplotlib.pyplot as plt
Explanation: GRIB Data Example
GRIB format is commonly used to disemminate atmospheric model data. With Xarray and the cfgrib engine, GRIB data can easily be analyzed and visualized.
End of explanation
ds = xr.tutorial.load_dataset('era5-2mt-2019-03-uk.gr... |
10,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advance Data Types
This section will cover the following advance topics in data types
Collections
Collections
The collections module is a tresure trove of a built-in module that implements s... | Python Code:
import collections
# from collections import ChainMap
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Individual Values')
print('a = {}'.format(m['a']))
print('b = {}'.format(m['b']))
print('c = {}'.format(m['c']))
print("-"*20)
print(type(m.keys()))
print('Keys = {}... |
10,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a bqplot recreation of Mike Bostock's Wealth of Nations. This was also done by Gapminder. It is originally based on a TED Talk by Hans Rosling.
Step1: Cleaning and Formatting JSON D... | Python Code:
import pandas as pd
import numpy as np
import os
from bqplot import (
LogScale, LinearScale, OrdinalColorScale, ColorAxis,
Axis, Scatter, Lines, CATEGORY10, Label, Figure, Tooltip
)
from ipywidgets import HBox, VBox, IntSlider, Play, jslink
initial_year = 1800
Explanation: This is a bqplot recreati... |
10,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Introduction
Doppler cooling is one of the most important experimental techniques in cold atom science. Perhaps it's indicative of the impact of this technology that at least five of ... | Python Code:
class GaussianBeam(object):
A laser beam with a Gaussian intensity profile.
def __init__(self, S0, x0, k, sigma):
Construct a Gaussian laser beam from position, direction, and width.
S0 -- Peak intensity (in units of the saturation intensity).
x0 -- A location ... |
10,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data analysis tools - Pearson correlation coefficient
For Week 3 assignment I'm testing association between average country income per person and average oil usage rate.
Step1: Following bl... | Python Code:
%matplotlib inline
import pandas
import numpy
import seaborn
import scipy
import matplotlib.pyplot as plt
data = pandas.read_csv('gapminder.csv', low_memory=False)
data['oilperperson'] = pandas.to_numeric(data['oilperperson'], errors='coerce')
data['incomeperperson'] = pandas.to_numeric(data['incomeperpers... |
10,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 6 – Decision Trees
This notebook contains all the sample code and solutions to the exercices in chapter 6.
Setup
First, let's make sure this notebook works well in both python 2 and ... | Python Code:
#Advanced: Using other libs...
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import numpy.random as rnd
import os
# to make this notebook's output stable across runs
rnd.seed(42)
# To plot pretty figures
%matplo... |
10,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notes on the LRIS Blue reduction
Step1: Detectors
Note
Step2: Display Raw LRIS image in Ginga | Python Code:
# imports
sys.path.append(os.path.abspath('/Users/xavier/local/Python/PYPIT/src'))
import arload as pyp_arload
import ario as pyp_ario
Explanation: Notes on the LRIS Blue reduction
End of explanation
fil = '/Users/xavier/PYPIT/LRIS_blue/Raw/b150910_2033.fits.gz'
hdu = fits.open(fil)
hdu.info()
head0['OBSTY... |
10,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Machine Learning
LA Team Submission 3 ##
Lukas Mosser, Alfredo De la Fuente
In this python notebook we explore a facies classification model using Deep Neural Net... | Python Code:
%%sh
pip install pandas
pip install scikit-learn
pip install keras
from __future__ import print_function
import numpy as np
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dro... |
10,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source localization with MNE/dSPM/sLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
inverse method such as MNE/dSPM/sLORETA on evoked/raw/epochs data.
Step1:... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import (make_inverse_operator, apply_inverse,
write_inverse_operator)
# sphinx_gallery_thumbnail_number = 9
Explanation: Source localization with MNE/dSPM/sLORET... |
10,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hydrometrics
In this notebook, we show how to compute several hydrometics parameters based on stream network produced from model. The analysis relies on the flow files (i.e. stream) found i... | Python Code:
%matplotlib inline
from matplotlib import cm
# Import badlands grid generation toolbox
import pybadlands_companion.hydroGrid as hydr
# display plots in SVG format
%config InlineBackend.figure_format = 'svg'
Explanation: Hydrometrics
In this notebook, we show how to compute several hydrometics parameters b... |
10,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Account Information | Contents | Trade Management >
Order Management
OANDA REST-V20 API wrapper doc on Order
OANDA API Getting Started
OANDA API Order
Create an Order for... | Python Code:
import pandas as pd
import oandapyV20
import oandapyV20.endpoints.orders as orders
import configparser
config = configparser.ConfigParser()
config.read('../config/config_v20.ini')
accountID = config['oanda']['account_id']
access_token = config['oanda']['api_key']
client = oandapyV20.API(access_token=access... |
10,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plots for SFR-Stellar Mass-Size Paper
This is an outline of the results that will go into the first paper. The first paper will focus on the $$SFR-M_{*}-Size$$ relation, where $$Size \equiv... | Python Code:
import numpy as np
from pylab import *
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
Explanation: Plots for SFR-Stellar Mass-Size Paper
This is an outline of the results that will go into the first paper. The first paper will focus on the $$SFR-M_{*}-Size$$ relation, where $$Size \e... |
10,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TF.Text Metrics
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: ROUGE-L
The Rouge-L metric ... | 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... |
10,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cams', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: CAMS
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
10,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Datasets
TFDS provides a collection of ready-to-use datasets for use with TensorFlow, Jax, and other Machine Learning frameworks.
It handles downloading and preparing the data det... | Python Code:
!pip install -q tfds-nightly tensorflow matplotlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
Explanation: TensorFlow Datasets
TFDS provides a collection of ready-to-use datasets for use with TensorFlow, Jax, and other Machine Learning fram... |
10,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction with SVMs over SLM.
In this notebook I confirm that the good performance that I get with the letters does not depend on some quirk involved with the fact that the letters (that is... | Python Code:
import numpy as np
import h5py
from sklearn import svm, cross_validation, preprocessing
# First we load the file
file_location = '../results_database/text_wall_street_big.hdf5'
run_name = '/low-resolution'
f = h5py.File(file_location, 'r')
# Now we need to get the letters and align them
text_directory = '... |
10,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: Now define a count_letters(n) that return... | Python Code:
x = list(one, two, three)
x
def number_to_words(n):
Given a number n between 1-1000 inclusive return a list of words for the number.
Explanation: Project Euler: Problem 17
https://projecteuler.net/problem=17
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there ar... |
10,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
About arithmetic accuracy in Python
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Integers" data-toc-modified-id="Integers... | Python Code:
x = 7**273
print(x)
print(type(x))
Explanation: About arithmetic accuracy in Python
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Integers" data-toc-modified-id="Integers-1"><span class="toc-item-num">1 </span><a href="https://d... |
10,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reusable components
This tutorial describes the manual way of writing a full component program (in any language) and a component definition for it. Below is a summary of the steps involved i... | Python Code:
import kfp
import kfp.gcp as gcp
import kfp.dsl as dsl
import kfp.compiler as compiler
import kfp.components as comp
import datetime
import kubernetes as k8s
# Required Parameters
PROJECT_ID='<ADD GCP PROJECT HERE>'
GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>'
Explanation: Reusable components
This tutoria... |
10,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Now that you are familiar with the coding environment, it's time to learn how to make your own charts!
In this tutorial, you'll learn just enough Python to create professional looking line... | Python Code:
#$HIDE$
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
print("Setup Complete")
Explanation: Now that you are familiar with the coding environment, it's time to learn how to make your own charts!
In this tutorial, y... |
10,168 | 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', 'mri', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MRI
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties: 85... |
10,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Beaming and Boosting
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 t... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: Beaming and Boosting
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 of explanation
%matplotlib inlin... |
10,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Data Generation
Data is generated from a 2D mixture of Gaussians.
Step2: Plotting
Step3: Models and Training
A multilayer perceptron with the ReLU activation functio... | Python Code:
!pip install -q flax
from typing import Sequence
import matplotlib.pyplot as plt
import jax
import jax.numpy as jnp
try:
import flax.linen as nn
except ModuleNotFoundError:
%pip install -qq flax
import flax.linen as nn
from flax.training import train_state
try:
import optax
except ModuleNot... |
10,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Performing the Hyperparameter tuning
Learning Objectives
1. Learn how to use cloudml-hypertune to report the results for Cloud hyperparameter tuning trial runs
2. Learn how to configure the ... | Python Code:
# Use the chown command to change the ownership of the repository
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Installing the latest version of the package
!pip install --user google-cloud-bigquery==1.25.0
Explanation: Performing the Hyperparameter tuning
Learning Objectives
1. Lear... |
10,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple data representations
Before we delve into learnable data representations, feature crosses, etc., let’s look at simpler data representations. We can think of these simple data represen... | Python Code:
from sklearn import datasets, linear_model
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
raw = diabetes_X[:, None, 2]
max_raw = max(raw)
min_raw = min(raw)
scaled = (2*raw - max_raw - min_raw)/(max_raw - min_raw)
def train_raw():
linear_model.LinearRegression().fit(raw, diabetes_y)
d... |
10,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First example
Step1: Note that we also chose a grid to solve the equation on. The $x$ and $y$ coordinates can be obtained by
Step2: To integrate in time we need an initial state. Equations... | Python Code:
equation = pde.advection.equations.FiniteVolumeAdvectionDiffusion(diffusion_coefficient=0.01)
grid = grids.Grid.from_period(size=256, length=2*np.pi)
Explanation: First example: Advection diffusion
In this example we'll see how to integrate in time a pre-defined equation. Here we deal with the Advection-Di... |
10,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A half-baked tutorial on ensemble methods
<center>by Ivan Nazarov<center/>
This tutorial covers both introductiory level theory underpinning
each ensemble method, as well as the tools availa... | Python Code:
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.utils import check_random_state
Explanation: A half-baked tutorial on ensemble methods
<center>by Ivan Nazarov<center/>
This tutorial covers both introductiory level theory underpinning
each ensemble met... |
10,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Is Unique
Is Unique
Step1: Check Permutation
Check Permutation
Step2: Palindrome Permutation
Step3: Palindrome Permutation
Given a string, write a function to check if it is a permutation... | Python Code:
import random
#STR = random.uniform(('a').encode('ascii'), int('Z'))
#print(ord('A'))
#print(ord('z'))
#lowercase = [ chr(char) for char in range(ord('a'), ord('z') + 1)]
#uppercase = [ chr(char) for char in range(ord('A'), ord('Z') + 1)]
#string_seed = lowercase + uppercase
#print(string_seed)
def gen_ran... |
10,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create all the columns of the dataframe as series
Step2: Create a dictionary variable that assigns variable names
Step3: Create a dataframe and set the order of the columns u... | Python Code:
import pandas as pd
Explanation: Title: Count Values In Pandas Dataframe
Slug: pandas_dataframe_count_values
Summary: Count Values In Pandas Dataframe
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
Import the pandas module
End of explanation
year = pd.Series([1875, 1876... |
10,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Activité
Step1: Ajouter un cube a coté du mini_dof
Step2: L'objectif est d'éloigner le cube le long de l'axe y.
L'équipe qui déplace le cube le plus loin gagne !
Première methode, par ta... | Python Code:
from poppy.creatures import Poppy4dofArmMini
mini_dof = Poppy4dofArmMini(simulator='vrep')
Explanation: Activité : déplacer un objet à l'aide d'un bras robotisé
Compétences visées par cette activité :
Résoudre un problème par l'expérimentation. Comparer l'approche par l'expérimentation avec avec l'approche... |
10,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating Synthetic Data
In data analysis, it is important that we have the ability to test our assumptions. One powerful tool to enable these tests is simulation. In 3ML, we have several w... | Python Code:
from threeML import *
import numpy as np
%matplotlib inline
jtplot.style(context="talk", fscale=1, ticks=True, grid=False)
import matplotlib.pyplot as plt
plt.style.use("mike")
import warnings
warnings.simplefilter("ignore")
# Select an astromodels function to from which to simualte
generating_function = P... |
10,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Load software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Initial loading of the data
Step5: Laser alternation selection
At t... | Python Code:
ph_sel_name = "all-ph"
data_id = "22d"
# ph_sel_name = "all-ph"
# data_id = "7d"
Explanation: Executed: Mon Mar 27 11:34:36 2017
Duration: 8 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
fro... |
10,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learn About Kernels
Do some SVM Classification
Step1: Can try it with Outliers if we have time
Let's look at some spectra
Step2: Notice that these training sets are unbalanced
Step3: Does... | Python Code:
from sklearn.svm import SVC
### SVC wants a 1d array, not a column vector
Targets = np.ravel(TargetOutputs)
InitSVM = SVC()
InitSVM
TrainedSVM = InitSVM.fit(AllSamps, Targets)
y = TrainedSVM.predict(AllSamps)
plt.figure(1)
plt.plot(y)
plt.show()
d = TrainedSVM.decision_function(AllSamps)
plt.figure(1)
plt.... |
10,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Apache Drill - Hansard Demo
Download and install Apache Drill.
Start Apache Drill in the Apache Drill directory
Step1: Make things faster
We can get a speed up on querying the CSV file by c... | Python Code:
#Download data file
!wget -P /Users/ajh59/Documents/parlidata/ https://zenodo.org/record/579712/files/senti_post_v2.csv
#Install some dependencies
!pip3 install pydrill
!pip3 install pandas
!pip3 install matplotlib
#Import necessary packages
import pandas as pd
from pydrill.client import PyDrill
#Set the n... |
10,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supervised Learning
Step1: Step 2
Step2: Now we can make out a slight trend that price increases along with the number of rooms in that house, which intuitively makes sense! Now let's use ... | Python Code:
# Standard imports
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
# Plotting
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
# scikit learn
import sklearn
from sklearn.datasets import load_boston
# Load the housing data sets
b... |
10,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../../images/qiskit-heading.gif" alt="Note
Step1: We first set the number of qubits used in the experiment, and the hidden integer $a$ to be found by the Bernstein-Vazirani algori... | Python Code:
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, get_backend
from qiskit.wrapper.jupyter impor... |
10,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using KNearestNeighbors (submission 2)
<a rel="license" href="https
Step1: Load training data
Step2: Build features
In the real world it would be unusual to have neut... | Python Code:
import pandas as pd
import numpy as np
from sklearn import neighbors
from sklearn import preprocessing
from sklearn.model_selection import LeaveOneGroupOut
import inversion
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Explanation: Facies classification using KNearestNeighbors (s... |
10,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Milestone report
Instruction
You have proposed a project, collected a data set, cleaned up the data and explored it with descriptive and inferential statistics techniques. Now’s the time to ... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
sns.set_style('white')
Explanation: Milestone report
Instruction
You have proposed a project, collected a data set, cleaned up the data and explored it with... |
10,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src='https
Step1: or...
Step2: For parallel computing in python, map is a key abstraction.
Step3: lambda
Anonymous function
Step4: reduce
Apply a function with two arguments cumulat... | Python Code:
def square(x):
return x*x
numbers = [1,2,3]
def map_squares(nums):
res = []
for x in nums:
res.append( square(x) )
return res
map_squares(numbers)
Explanation: <img src='https://www.rc.colorado.edu/sites/all/themes/research/logo.png'>
Introduction to Spark
Many examples courtesy Mon... |
10,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the NYC Subway Dataset
Intro to Data Science
Step1: Functions for Getting, Mapping, and Plotting Data
Step2: Function for Basic Statistics
Step3: Formulas Implemented
(i.e., not... | Python Code:
import inflect # for string manipulation
import numpy as np
import pandas as pd
import scipy as sp
import scipy.stats as st
import matplotlib.pyplot as plt
%matplotlib inline
filename = '/Users/excalibur/py/nanodegree/intro_ds/final_project/improved-dataset/turnstile_weather_v2.csv'
# import data
data = pd... |
10,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Surface Observations in Siphon and MetPy
What is METAR?
Surface observational data
Access via a URL constructed from a web form
Returns csv, xml, or NetCDF formatted data
http
S... | Python Code:
%matplotlib inline
import numpy as np
from datetime import datetime, timedelta
Explanation: Working with Surface Observations in Siphon and MetPy
What is METAR?
Surface observational data
Access via a URL constructed from a web form
Returns csv, xml, or NetCDF formatted data
http://thredds.ucar.edu/thredds... |
10,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Analyzing Shreddit's Q2 Top 5 voting
This started out as a curiosity. I was interested in what I'd need to do to take a bunch of "Top X" lists, combine them and then ask questions to ... | Python Code:
# set up all the data for the rest of the notebook
import json
from collections import Counter
from itertools import chain
from IPython.display import HTML
def vote_table(votes):
Render a crappy HTML table for easy display. I'd use Pandas, but that seems like
complete overkill for this simple task.... |
10,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyPanair Tutorial#2 Tapered Wing
In this tutorial we will perform an analysis of a tapered wing.
The wing is defined by five different wing sections at $\eta=0.000, 0.126, 0.400, 0.700, 1.00... | Python Code:
%matplotlib notebook
import matplotlib.pyplot as plt
from pyPanair.preprocess import wgs_creator
for eta in ("0000", "0126", "0400", "0700", "1000"):
af = wgs_creator.read_airfoil("eta{}.csv".format(eta))
plt.plot(af[:,0], af[:,2], "k-", lw=1.)
plt.plot((0.5049,), (0,), "ro", label="Center of rota... |
10,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
데이터 시각화
Step1: 주요 내용
데이터 분석을 위해 가장 기본적으로 할 수 있고, 해야 하는 일이 데이터 시각화이다.
데이터를 시각화하는 것은 어렵지 않지만, 적합한 시각화를 만드는 일은 매우 어려우며,
많은 훈련과 직관이 요구된다.
여기서는 데이터를 탐색하여 얻어진 데이터를 시각화하는 기본적인 방법 네 가지를 배운다.
선그래프
... | Python Code:
from __future__ import division, print_function
Explanation: 데이터 시각화
End of explanation
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: 주요 내용
데이터 분석을 위해 가장 기본적으로 할 수 있고, 해야 하는 일이 데이터 시각화이다.
데이터를 시각화하는 것은 어렵지 않지만, 적합한 시각화를 만드는 일은 매우 어려우며,
많은 훈련과 직관이 요구된다.
여기서는 데이터를 탐색하여 얻어진 데이터를 시각화하는 기본적인 ... |
10,192 | 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="#Maximum-Inner-Product" data-toc-modified-id="Maximum-Inner-Product-1"><span ... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', '..', 'notebook_format'))
from formats import load_style
load_style(css_style='custom2.css', plot_style=False)
os.chdir(path)
# 1. magic for in... |
10,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 3
Imports
Step2: Contour plots of 2d wavefunctions
The wavefunction of a 2d quantum well is
Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 3
Imports
End of explanation
def well2d(x, y, nx, ny, L=1.0):
Compute the 2d quantum well wave function.
return (2/L) * np.sin((nx * np.pi * x)/L) * np.sin((ny * np.pi * y)/L)
psi = well2d(np.lins... |
10,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Support Vector Machines
Let's create the same fake income / age clustered data that we used for our K-Means clustering example
Step1: Now we'll use linear SVC to partition our graph into cl... | Python Code:
import numpy as np
#Create fake income/age clusters for N people in k clusters
def createClusteredData(N, k):
pointsPerCluster = float(N)/k
X = []
y = []
for i in range (k):
incomeCentroid = np.random.uniform(20000.0, 200000.0)
ageCentroid = np.random.uniform(20.0, 70.0)
... |
10,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Teste de BI
Candidato
Step1: 1. Usando mtcars, trazer a média de miles per galon da marca Mercedez. Atribuir isso a uma variável x.
Step2: 2. Testar se há correlação entre o peso do carro ... | Python Code:
# Links para as bases de dados do R:
mtcars_link = 'https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/mtcars.csv'
quakes_link = 'https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/quakes.csv'
cars_link = 'https://raw.github.com/vincentarelbundock/Rdatas... |
10,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Widget Events
In this lecture we will discuss widget events, such as button clicks!
Special events
Step1: The Button is not used to represent a data type. Instead the button widget is used... | Python Code:
from __future__ import print_function
Explanation: Widget Events
In this lecture we will discuss widget events, such as button clicks!
Special events
End of explanation
import ipywidgets as widgets
print(widgets.Button.on_click.__doc__)
Explanation: The Button is not used to represent a data type. Instead... |
10,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculate Jensen-Shannon Divergence Between Luke and John
The KL Divergence between two discrete distributions $P$ and $Q$ with pdfs $p$ and $q$, defined over the same sample space $X={x_0,x... | Python Code:
from PIL import Image
import numpy as np
luke = Image.open("/home/nathan/Downloads/Luke_Van_Poppering.jpeg")
luke.thumbnail((300,300)) # Thanks for this, John....
john = Image.open("/home/nathan/Downloads/John_Abascal.jpg")
john.thumbnail((300,300))
luke
john
Explanation: Calculate Jensen-Shannon Divergenc... |
10,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python入门 第一周和第二周的练习
练习
回答下列粗体文字所描述的问题,如果需要,使用任何合适的方法,以掌握技能,完成自己想要的程序为目标,不用太在意实现的过程。
7 的四次方是多少?
分割以下字符串
s = "Hi there Sam!"
到一个列表中
提供了一下两个变量
planet = "Earth"
diameter = 12742
使用forma... | Python Code:
planet = "Earth"
diameter = 12742
Explanation: Python入门 第一周和第二周的练习
练习
回答下列粗体文字所描述的问题,如果需要,使用任何合适的方法,以掌握技能,完成自己想要的程序为目标,不用太在意实现的过程。
7 的四次方是多少?
分割以下字符串
s = "Hi there Sam!"
到一个列表中
提供了一下两个变量
planet = "Earth"
diameter = 12742
使用format()函数输出一下字符串
The diameter of Earth is 12742 kilometers.
End of explan... |
10,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.