Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
11,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
================================================================
Compute sparse inverse solution with mixed norm
Step1: Run solver
Step2: Plot dipole activations
Step3: Plot residual
Step... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles
from mne.minimum_norm import ma... |
11,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graphs and visualization
A lot of the joy of digital humanities comes in handling our material in new ways, so that we see things we wouldn't have seen before. Quite literally.
Some of the m... | Python Code:
# This is how you get the %%dot command that we use below.
%load_ext hierarchymagic
Explanation: Graphs and visualization
A lot of the joy of digital humanities comes in handling our material in new ways, so that we see things we wouldn't have seen before. Quite literally.
Some of the most useful tools f... |
11,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
O$_2$scl table example for O$_2$sclpy
See the O$_2$sclpy documentation at
https
Step1: Link the o2scl library
Step2: Create an HDF5 file object and open the table in O$_2$scl's data file f... | Python Code:
import o2sclpy
import matplotlib.pyplot as plot
import sys
plots=True
if 'pytest' in sys.modules:
plots=False
Explanation: O$_2$scl table example for O$_2$sclpy
See the O$_2$sclpy documentation at
https://neutronstars.utk.edu/code/o2sclpy for more information.
End of explanation
link=o2sclpy.linker()
l... |
11,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EXP 3-NYCtaxi
In this experiment we use the NYC taxi dataset. We pass it through a scalar encoder, spatial pooler and then to the TM. We do a single pass to the TM and keep track of the spik... | Python Code:
import numpy as np
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from nupic.encoders import ScalarEncoder
from nupic.bindings.algorithms import TemporalMemory as TM
from nupic.bindings.algorithms import SpatialPooler as SP
from htmresearch.support... |
11,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create the input required for a full TranSiesta calculation. Here you should create your first system with these settings
Step1: Create the electrode.
Supply the coordinates and the super... | Python Code:
C = sisl.Atom(6)
Explanation: Create the input required for a full TranSiesta calculation. Here you should create your first system with these settings:
A pristine bulk Carbon-chain system.
The Carbon-chain should have a bond-length of $1.5\,\mathrm{Ang}$ and lots of vacuum in the transverse directions (to... |
11,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
15/10
Características del Python. Lenguajes compilados vs interpretados. Tipado estático vs dinámico. Fuertemente tipado vs débilmente tipado.
Variables. Operaciones Elementales. Tipos de Da... | Python Code:
numero_entero = 5 # Asigno el número 5 a la variable numero_entero
print numero_entero # Imprimo el valor que tiene la variable numero_entero
print type(numero_entero) # Imprimo el tipo de la variable numero_entero
Explanation: 15/10
Características del Python. Lenguajes compilados vs inte... |
11,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Unfortunately simply reporting the sample mean doesn't do much for us, as we don't know how it relates to the population mean. To get a sense for how it might relate, we can... | Python Code:
import numpy as np
import seaborn as sns
from scipy import stats
import matplotlib.pyplot as plt
# We'll set a seed here so our runs are consistent
np.random.seed(10)
# Let's define some 'true' population parameters, we'll pretend we don't know these.
POPULATION_MU = 64
POPULATION_SIGMA = 5
# Generate our ... |
11,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix generation
Init symbols for sympy
Step1: Lame params
Step2: Metric tensor
${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$
Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_... | Python Code:
from sympy import *
from geom_util import *
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True)
init_printing()
%matplotlib inline
%reload_ext autoreload
%autoreload 2
%aimport geom_util
Explanation: Matrix generati... |
11,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework
Step1: Part 1
Step2: Part 3 | Python Code:
! curl https://raw.githubusercontent.com/mafudge/datasets/master/ist256/08-Lists/test-fudgemart-products.txt -o test-fudgemart-products.txt
! curl https://raw.githubusercontent.com/mafudge/datasets/master/ist256/08-Lists/fudgemart-products.txt -o fudgemart-products.txt
Explanation: Homework: The Fudgemart ... |
11,809 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section3a - Dataset preparation
We will start by deciding which features we want to use in the machine learning prediction of the severity of the accident for each user.
We'll also do a fina... | Python Code:
import pandas as pd
import numpy as np
# Provides better color palettes
import seaborn as sns
from pandas import DataFrame,Series
import matplotlib as mpl
import matplotlib.pyplot as plt
# Command to display the plots in the iPython Notebook
%matplotlib inline
import matplotlib.patches as mpatches
mpl.styl... |
11,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Cloud Natural Language API を使ってみよう !
Cloud Natural Language API は、エンティティ分析、感情分析、コンテンツ分類、構文解析などの自然言語を理解するための技術をデベロッパーに提供します。
API Discovery Service を利用して Cloud Natural L... | Python Code:
import getpass
APIKEY = getpass.getpass()
Explanation: <a href="https://colab.research.google.com/github/GoogleCloudPlatform/gcp-getting-started-lab-jp/blob/master/machine_learning/cloud_ai_building_blocks/language_ja.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.sv... |
11,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook shows how to use the output from VASP DFPT calculation and the phonopy interface to plot the phonon bandstructure and density of states.
Requires
Step1: Set the structure
Step... | Python Code:
import os
import numpy as np
import pymatgen as pmg
from pymatgen.io.vasp.outputs import Vasprun
from phonopy import Phonopy
from phonopy.structure.atoms import Atoms as PhonopyAtoms
%matplotlib inline
Explanation: This notebook shows how to use the output from VASP DFPT calculation and the phonopy interfa... |
11,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Display Exercise 1
Imports
Put any needed imports needed to display rich output the following cell
Step1: Basic rich display
Find a Physics related image on the internet and display it in t... | Python Code:
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this to grade the import statements
Explanation: Display Exercise 1
Imports
Put any needed imports needed to display rich output the following cell:
End of explanation
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this to g... |
11,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Вопросы
Назовите несколько видов баз данных и опишите, в чем их суть.
Что такое транзакция в терминах баз данных?
Что делает следующий запрос?
SQL
SELECT * FROM employees, managers WHERE emp... | Python Code:
import numpy as np
np.zeros(10) # вектор из 10 нулевых элементов
np.arange(9).reshape(3,3) # матрица 3х3 с числами от 0 до 8
m = np.eye(3) # единичная матрица
m.shape # размеры матрицы
a = np.random.random((3,3,3)) # трехмерная матрица 3x3x3 со случайными значениями
# Матрица numpy - многомерный массив и п... |
11,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's look at seemingly impossible example where 80% of hidden, true positive labels have been flipped to negative! Also, let 15% of negative labels be flipped to positive!
Feel free to adju... | Python Code:
# Choose mislabeling noise rates.
frac_pos2neg = 0.8 # rh1, P(s=0|y=1) in literature
frac_neg2pos = 0.15 # rh0, P(s=1|y=0) in literature
# Combine data into training examples and labels
data = neg.append(pos)
X = data[["x1","x2"]].values
y = data["label"].values
# Noisy P̃Ñ learning: instead of target y, w... |
11,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lago SDK Example - one VM one Network
Step2: Create a LagoInitFile, normally this file should be saved to the disk. Here we will use a temporary file instead. Our environment includes one C... | Python Code:
import logging
import tempfile
from textwrap import dedent
from lago import sdk
Explanation: Lago SDK Example - one VM one Network
End of explanation
with tempfile.NamedTemporaryFile(delete=False) as init_file:
init_file.write(dedent(
domains:
vm-01:
memory: 1024
nics:
... |
11,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute MNE-dSPM inverse solution on single epochs
Compute dSPM inverse solution on single trial epochs restricted
to a brain label.
Step1: View activation time-series to illustrate the ben... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.minimum_norm import apply_invers... |
11,817 | 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 Email Addresses
Slug: match_email_addresses
Summary: Match Email Addresses
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon
Based on: StackOverflow
Preliminaries
End of explanation
# Create a variable containing a text strin... |
11,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summarize the reviews
The idea in this solution is to provide a new feature to the customer which will reduce the need to go through several reviews in order to evaluate a product. In order ... | Python Code:
all_reviews = (spark
.read
.json('./data/raw_data/reviews_Baby_5.json.gz',)
.na
.fill({ 'reviewerName': 'Unknown' }))
from pyspark.sql.functions import col, expr, udf, trim
from pyspark.sql.types import IntegerType
import re
remove_punctuation = udf(lambda line: re.sub('[^A-Za-z\s]', '', li... |
11,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Started some more runs with extra MLP layers, with varying levels of Dropout in each. Casually looking at the traces when they were running, it looked like the model with lower dropout conve... | Python Code:
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import holoviews as hl
%load_ext holoviews.ipython
import sklearn.metrics
Explanation: Started some more runs with ext... |
11,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note
Step1: Now I'll simulate it
Step2: The simulation was set up with a three-bit threshold having a value of three.
The counter has the same number of bits as the threshold, so it will c... | Python Code:
from pygmyhdl import *
@chunk
def pwm_simple(clk_i, pwm_o, threshold):
'''
Inputs:
clk_i: PWM changes state on the rising edge of this clock input.
threshold: Bit-length determines counter width and value determines when output goes low.
Outputs:
pwm_o: PWM output starts... |
11,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple example of using Facebook's Prophet
We will use public road traffic data to train the model and forecast future road traffic.
Main intention is to show how simple Prophet usage is, fo... | Python Code:
from fbprophet import Prophet
import pandas as pd
%matplotlib notebook
import matplotlib
Explanation: Simple example of using Facebook's Prophet
We will use public road traffic data to train the model and forecast future road traffic.
Main intention is to show how simple Prophet usage is, forecast itself i... |
11,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder on MNIST dataset
Learning Objective
1. Build an autoencoder architecture (consisting of an encoder and decoder) in Keras
2. Define the loss using the reconstructive... | Python Code:
from __future__ import absolute_import, division, print_function
import glob
import imageio
import os
import PIL
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers
from IPython import display
Explanation: Convolutional Autoencoder on M... |
11,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary
Do I sleep less on nights when I play Ultimate frisbee?
Step1: Lots of variation here. Can I relate this to Ultimate frisbee? Spring hat league started on April 14 and played once a... | Python Code:
import pandas as pd
import os
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import nba_py
sns.set_context('poster')
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
data_path = os.path.join(os.getcwd(), os.pardir, 'data', 'interim',... |
11,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating my own version of the dogs_cats_redux notebook in order to make my own entry into the Kaggle competition.
My dir structure is similar, but not exactly the same
Step1: Note
Step2: ... | Python Code:
#Verify we are in the lesson1 directory
%pwd
%matplotlib inline
import os, sys
sys.path.insert(1, os.path.join(sys.path[0], '../utils'))
from utils import *
from vgg16 import Vgg16
from PIL import Image
from keras.preprocessing import image
from sklearn.metrics import confusion_matrix
Explanation: Creating... |
11,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3D Plots, in Python
We first load in the toolboxes for numerical python and plotting.
Step1: Plotting a simple surface.
Let's plot the hyperbola $z = x^2 - y^2$.
The 3D plotting commands e... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Explanation: 3D Plots, in Python
We first load in the toolboxes for numerical python and plotting.
End of explanation
# Make data
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.m... |
11,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-2', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: NIMS-KMA
Source ID: SANDBOX-2
Topic: Ocean
Sub-Topics: Timestepping Frame... |
11,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SYDE 556/750
Step1: Some sort of mapping between neural activity and a state in the world
my location
head tilt
image
remembered location
Intuitively, we call this "representation"
In neuro... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('KE952yueVLA', width=720, height=400, loop=1, autoplay=0)
from IPython.display import YouTubeVideo
YouTubeVideo('lfNVv0A8QvI', width=720, height=400, loop=1, autoplay=0)
Explanation: SYDE 556/750: Simulating Neurobiological Systems
Accompanying Reading... |
11,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference
Step1: impo... | Python Code:
import pandas as pd
Explanation: JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference: http://pandas-docs.github.io/pandas-docs-travis/io.html#json
data source: http://jsonstudio.com... |
11,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
Neural Network Exercises - SOLUTIONS
For these exercises we'll p... | Python Code:
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
%matplotlib inline
df = pd.read_csv('../Data/income.csv')
print(len(df))
df.head()
df['label'].value_counts()
Explanation: <img src="../Pierian-Data-Logo.PNG">
<br>
<s... |
11,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started with ActivitySim
This getting started guide is a Jupyter notebook. It is an interactive Python 3 environment that describes how to set up, run, and begin to analyze the resul... | Python Code:
!conda create -n asim python=3.9 activitysim -c conda-forge --override-channels
Explanation: Getting Started with ActivitySim
This getting started guide is a Jupyter notebook. It is an interactive Python 3 environment that describes how to set up, run, and begin to analyze the results of ActivitySim modeli... |
11,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fixed End Forces
This module computes the fixed end forces (moments and shears) due to transverse loads
acting on a 2-D planar structural member.
Step7: Class EF
Instances of class EF repre... | Python Code:
import numpy as np
import sys
from salib import extend
Explanation: Fixed End Forces
This module computes the fixed end forces (moments and shears) due to transverse loads
acting on a 2-D planar structural member.
End of explanation
class EF(object):
Class EF represents the 6 end forces acting on ... |
11,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the flexible path length simulation
Step1: Load the file, and from the file pull our the engine (which tells us what the timestep was) and the move scheme (which gives us a starti... | Python Code:
from __future__ import print_function
%matplotlib inline
import openpathsampling as paths
import numpy as np
import matplotlib.pyplot as plt
import os
import openpathsampling.visualize as ops_vis
from IPython.display import SVG
Explanation: Analyzing the flexible path length simulation
End of explanation
#... |
11,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting whitened data
This tutorial demonstrates how to plot
Step1: Raw data with whitening
<div class="alert alert-info"><h4>Note</h4><p>In the
Step2: Epochs with whitening
Step3: Evo... | Python Code:
import mne
from mne.datasets import sample
Explanation: Plotting whitened data
This tutorial demonstrates how to plot :term:whitened <whitening> evoked
data.
Data are whitened for many processes, including dipole fitting, source
localization and some decoding algorithms. Viewing whitened data thus gi... |
11,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Image Analysis with <font color='DarkBlue'>Python.</font>
<font color='brown'>Reading images</font>
Exercise
Step1: <font color='brown'>Reading a multi-page tiff</font>
Exer... | Python Code:
#This line is very important: (It turns on the inline visuals)!
%pylab inline
#This library is one of the libraries one can use for importing tiff files.
#For detailed info:http://effbot.org/imagingbook/image.htm
from PIL import Image
#We import our cell_fluorescent.tif image
im = Image.open('cell_fluoresc... |
11,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring Quantopian
There is collaboration and a Python IDE directly on the site, which is how the user interacts with their data.
Both of us are brand new to the site, so we are exploring ... | Python Code:
import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt
%matplotlib inline
import requests
import datetime
from database import Database
db = Database()
#list of fortune 500 companies ticke symbols
chicago_companies = ['ADM', 'BA', 'WGN', 'UAL', 'SHLD',
... |
11,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Organize recording files by site
This notebook copies sound files (recordings) into the pumilio directory structure based on a csv file containing information about the time and location of ... | Python Code:
csv_filepath = ""
sound_directory = ""
source_directory = os.path.dirname(os.path.dirname(working_directory))
Explanation: Organize recording files by site
This notebook copies sound files (recordings) into the pumilio directory structure based on a csv file containing information about the time and locati... |
11,837 | 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: 예제 데이터셋 받기
MNIST 데이터셋으로 모델을 훈련하여 ... | 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... |
11,838 | 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
Orders
Creating Orders
create_order(self, account_id, **params)
Step1: For a detailed explanation of... | Python Code:
from datetime import datetime, timedelta
import pandas as pd
import oandapy
import configparser
config = configparser.ConfigParser()
config.read('../config/config_v1.ini')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']
oanda = oandapy.API(environment="practice",
... |
11,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment
Step1: General information on the Gapminder data
Step2: But the unemployment rate is not provided directly. In the database, the employment rate (% of the popluation) is availab... | Python Code:
# Load a useful Python libraries for handling data
import pandas as pd
import numpy as np
from IPython.display import Markdown, display
# Read the data
data_filename = r'gapminder.csv'
data = pd.read_csv(data_filename, low_memory=False)
data = data.set_index('country')
Explanation: Assignment: Making Data ... |
11,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple change detection using annual mean NDVI
This example notebook describes how to retrieve data for a small region and epoch of interest, concatenate data from available sensors and calc... | Python Code:
%pylab notebook
from __future__ import print_function
import datacube
import xarray as xr
from datacube.helpers import ga_pq_fuser
from datacube.storage import masking
from datacube.storage.masking import mask_to_dict
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import pyplot as plt... |
11,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial setup
Step1: Ploynomial Least-Squares Fit Algorithm
Step2: Mean-Square Error as Measure of Fit
Step3: Best Historical MSE = Best Future Performance?
Step4: Overfitting!
So what n... | Python Code:
## Setup the path for our codebase
import sys
sys.path.append( '../code/' )
## import our time_series codebase
import time_series.generated_datasets
import time_series.result_set
import time_series.algorithm
dataset_0 = time_series.generated_datasets.DSS[0]( 10 )
dataset_0.taxonomy
%matplotlib inline
impor... |
11,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pythonic pandas
Using a tutorial about fast flexible pandas.
The pandas Python package is an effective way to examine and manipulate data.
The source code is available on Github, and be sure... | Python Code:
import pandas as pd
pd.__version__
nrg = pd.read_csv('energy_consumption.csv'); nrg.describe(include='all')
Explanation: Pythonic pandas
Using a tutorial about fast flexible pandas.
The pandas Python package is an effective way to examine and manipulate data.
The source code is available on Github, and be ... |
11,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autonomous driving - Car detection
Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook... | Python Code:
import argparse
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import l... |
11,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Acho que esse gráfico do G1 tá errado
G1 São Paulo
Nível de água do Cantareira vai a 14,5%; todos reservatórios sobem
link da notícia
<!----->
Step3: A sabesp di... | Python Code:
from IPython.display import display, Image
## eis a imagem da notícia
infograficoG1 = Image('reservatorios1403.jpg')
display(infograficoG1)
Explanation: Acho que esse gráfico do G1 tá errado
G1 São Paulo
Nível de água do Cantareira vai a 14,5%; todos reservatórios sobem
link da notícia
<!---
E... |
11,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Copyright 2020 Sen Pei (Columbia University).
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Substantial Undocumented Infectio... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
11,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Loading and Processing Tutorial
Step2: Let’s quickly read the CSV and get the annotations in an (N, 2) array where N is the number of landmarks.
Step5: Dataset class
torch.utils.data.... | Python Code:
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# Ignore warnings
import warnings
warnin... |
11,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transform EEG data using current source density (CSD)
This script shows an example of how to use CSD
Step1: Load sample subject data
Step2: Plot the raw data and CSD-transformed raw data
S... | Python Code:
# Authors: Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
Explanation: Transform EEG data using current source density (CSD)
This script shows an e... |
11,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Disclaimer
Step1: Install requirements and login into the right email and project
Step2: Update Params
Step4: Generate and load sample GA dataset
Based on an anonymized public GA dataset.... | Python Code:
!python --version && gcloud components update
Explanation: Disclaimer: The following code demonstrates a sample model creation with AI Platform, based on GA-BQ export dataset. This is meant for inspiration only. We expect analysts/data scientists to identify the right set of features to create retargeted a... |
11,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Report 3
by Kaitlyn Keil and Kevin Zhang
April 2017
Data Science Spring 2017
For reference on the database used
Step2: We then create a function to read in our dataset and clean it, pruning... | Python Code:
from __future__ import print_function, division
import pandas as pd
import sys
import numpy as np
import math
import matplotlib.pyplot as plt
from sklearn.feature_extraction import DictVectorizer
%matplotlib inline
import seaborn as sns
from collections import defaultdict, Counter
import statsmodels.formul... |
11,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The Bitrepository quickstart is a package for quickly getting a basic fully functioning bitrepository reference system up on a localhost.
The quickstart will setup a bitreposito... | Python Code:
!docker run \
--detach \
--rm \
--env 'ACTIVEMQ_MIN_MEMORY=512' \
--env 'ACTIVEMQ_MAX_MEMORY=2048' \
--publish 61616:61616 \
--name activemq \
webcenter/activemq:5.12.0 \
/opt/activemq/bin/activemq console
Explanation: Introduction
The Bitrepository quickstart is a package ... |
11,852 | 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... |
11,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play ... | Python Code:
import gym
import tensorflow as tf
import numpy as np
Explanation: Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called Cart-Pole. In this game, a freely sw... |
11,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classes
So far you have learned about Python's core data types
Step1: One of the first things you do with a class is to define the _init_() method. The __init__() method sets the values for... | Python Code:
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
Explanation: Classes
So far you have learned about Python's core data types: strings, numbers, lis... |
11,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Init config
Select appropriate
Step1: Count number of tweets per day for every news, calculate cummulative diffusion
Step2: Plot diffusion for every day for all news together
Step3: Plot ... | Python Code:
client = pymongo.MongoClient("46.101.236.181")
db = client.allfake
# get collection names
collections = sorted([collection for collection in db.collection_names()])
Explanation: Init config
Select appropriate:
- database server (line 1): give pymongo.MongoClient() an appropriate parameter, else it is local... |
11,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Settings
Step1: Load Jobs Data, Index in Solr Jobs Core
Step2: Load Relevancy Judgements File
Step6: IR Metrics
Step7: Black Box Optimization
Step8: Run Optimizer Algorithm
Step9: The ... | Python Code:
#Settings
# The files below are in the root folder of this GitHub repo. Launch jupyter notebook from that folder
# in order to read these files: 'jupyter notebook'
# Note: this is an artificial set of jobs, these are not real jobs, but are representative of our data
# Job descriptions are omitted, but usua... |
11,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Halite is an online multiplayer game created by Two Sigma. In the game, four participants command ships to collect an energy source called halite. The player with the most halite at the en... | Python Code:
#$HIDE_INPUT$
from kaggle_environments import make, evaluate
env = make("halite", debug=True)
env.run(["random", "random", "random", "random"])
env.render(mode="ipython", width=800, height=600)
Explanation: Halite is an online multiplayer game created by Two Sigma. In the game, four participants command s... |
11,858 | 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: Lets start by first making two circuits
Step2: The above shows the OpenQASM for both circuits. These can be converted to qobj to... | Python Code:
# Import the QuantumProgram and our configuration
import math
from pprint import pprint
from qiskit import QuantumProgram
import Qconfig
Explanation: <img src="../../images/qiskit-heading.gif" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" wi... |
11,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris dataset (Clustering)
Authors
Written by
Step1: Reading Data
Step2: Separate Data
Step3: Scatter Plot Matrix
Step4: K Means (3 clusters) | Python Code:
#Libraries and Imports
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import preprocessing
Explanation: Iris dataset (Clustering)
Authors
Written by: Neeraj Asthana (under Professor Robert Brunner)
University of I... |
11,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import librairies
Step1: Workspace
Define workspace variable
Step2: After defining the workspace, every defined variables will be automatically updated to the workspace
Define some variabl... | Python Code:
import numpy as np
from ipywksp import workspace
import pandas as pd
Explanation: Import librairies
End of explanation
workspace(theme='light') # Define a workspace variable
Explanation: Workspace
Define workspace variable
End of explanation
# Define integers and float numbers
a1 = 1
a2 = 54
e = 47.5
Z = 4... |
11,861 | 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', 'dwd', 'mpi-esm-1-2-hr', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: DWD
Source ID: MPI-ESM-1-2-HR
Topic: Landice
Sub-Topics: Glaciers, Ic... |
11,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting bins from time, energy
May 2018
Summer on campus. Entire family swimming in the fountain.
I need to take sums over ranges in time and energy. The challenge is that I can't simply p... | Python Code:
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import imageio
import pandas as pd
import seaborn as sns
sns.set(style='ticks')
sys.path.append('../scripts/')
import bicorr as bicorr
import bicorr_plot as bicorr_plot
%load_ext autoreload
%autoreload 2
Explanation: Selecting bins fro... |
11,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: TensorFlow Lite による芸術的スタイル転送
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: コンテンツ画像とスタイル画像... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
11,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing Centrality
Step1: We are using a synthetic example to explore shortest paths. The figure above shows a simple raster which
can be thought of as two regions separated by two 'hills' ... | Python Code:
%matplotlib inline
# %load testShortestPath2.py
from rasterGraphCreate import *
import matplotlib
from matplotlib import pyplot
if __name__ == "__main__":
arraySize = 100
startNode = 4
destNode = 8080
startNode1 = 90
destNode1 = 8008
startNode2 = 30
destNode2 = 9080
ras... |
11,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
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', 'cnrm-cerfacs', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-3
Topic: Seaice
Sub-Topics: Dynamic... |
11,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Índice
Exclusão competitiva
Coexistência em equilíbrio
Step1: <div id="2">2. Coexistência em equilíbrio
Step2: <div id="3">3. Não-linearidade relativa</div>
Agora vamos voltar ao modelo da... | Python Code:
%matplotlib notebook
from numpy import *
from scipy.integrate import odeint
from matplotlib.pyplot import *
ion()
def consumer_resource1(y, t, r, K, b1, m1, b2, m2):
return array([ y[0] * (r*(1-y[0]/K) - b1*y[1] - b2*y[2]),
y[1] * (b1*y[0] - m1),
y[2] * (b2*y[0] - ... |
11,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parallelization
Step1: With emcee, it's easy to make use of multiple CPUs to speed up slow sampling.
There will always be some computational overhead introduced by parallelization so it wil... | Python Code:
import os
os.environ["OMP_NUM_THREADS"] = "1"
Explanation: Parallelization
End of explanation
import emcee
print(emcee.__version__)
Explanation: With emcee, it's easy to make use of multiple CPUs to speed up slow sampling.
There will always be some computational overhead introduced by parallelization so it... |
11,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Provide config file
Step1: Fires in Nepal
http
Step2: Further subset using bounding box | Python Code:
cmr=CMR("../cmr.cfg")
Explanation: Provide config file
End of explanation
results = cmr.searchGranule(entry_title='MODIS/Aqua Near Real Time (NRT) Thermal Anomalies/Fire 5-Min L2 Swath 1km (C005)',
temporal="2016-04-11T12:00:00Z,2016-04-11T13:00:00Z")
for res in results:
print(r... |
11,869 | Given the following text description, write Python code to implement the functionality described.
Description:
Minimum cost to build N blocks from one block
Function to calculate min cost to build N blocks ; Initialize base case ; Recurence when i is odd ; Recurence when i is even ; Driver code
| Python Code:
def minCost(n , x , y , z ) :
dp =[0 ] *(n + 1 )
dp[0 ] = dp[1 ] = 0
for i in range(2 , n + 1 ) :
if(i % 2 == 1 ) :
dp[i ] = min(dp [(i + 1 ) // 2 ] + x + z , dp[i - 1 ] + y )
else :
dp[i ] = min(dp[i // 2 ] + x , dp[i - 1 ] + y )
return dp[n ]
n = 5
x = 2
y = 1
z = 3
... |
11,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table style="width
Step1: Import and clean data
Set the directory path and look for all netcdf files that correspond to the model drivers and target.
Step2: Define a function to extract t... | Python Code:
# data munging and analytical libraries
import re
import os
import numpy as np
import pandas as pd
from netCDF4 import Dataset
# graphical libraries
import matplotlib.pyplot as plt
%matplotlib inline
# set paths
outPath = "../data/globfire.csv"
Explanation: <table style="width: 100%; border-collapse: col... |
11,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text-Fabric Api 활용예제 3
Step1: 성서 본문을 큰 단위의 word node가 아닌 각 단어 요소들로 잘라서 출력함
창세기 1
Step2: Text feature가 아닌 feature의 g_word_utf8의 값을 이용하여 첫 번째 word node 출력
Step4: 위를 응용하여 창세기 1
Step5: 창세기 1... | Python Code:
from tf.fabric import Fabric
ETCBC = 'hebrew/etcbc4c'
PHONO = 'hebrew/phono'
TF = Fabric( modules=[ETCBC, PHONO], silent=False )
api = TF.load('''
book chapter verse
sp nu gn ps vt vs st
otype
det
g_word_utf8 trailer_utf8
lex_utf8 lex voc_utf8
g_prs_utf8 g_uvf_utf8
prs_gn pr... |
11,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import datasets
import torchvision.transforms as transforms
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 64
# convert data to torch.Float... |
11,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Laboratoire d'introduction au filtrage - Corrigé
Cours NSC-2006, année 2015
Méthodes quantitatives en neurosciences
Pierre Bellec, Yassine Ben Haj Ali
Objectifs
Step1: Section 1
Step2: Re... | Python Code:
%matplotlib inline
from pymatbridge import Octave
octave = Octave()
octave.start()
%load_ext pymatbridge
Explanation: Laboratoire d'introduction au filtrage - Corrigé
Cours NSC-2006, année 2015
Méthodes quantitatives en neurosciences
Pierre Bellec, Yassine Ben Haj Ali
Objectifs:
Ce laboratoire a pour but ... |
11,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>Pandas
Step1: Combining data is essential functionality in a data analysis workflow.
Data is distributed in multiple files, different information needs to be merged, n... | Python Code:
import pandas as pd
Explanation: <p><font size="6"><b>Pandas: Combining datasets Part I - concat</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenbossche@gmail.... |
11,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example - FRET histogram fitting
This notebook is part of smFRET burst analysis software FRETBursts.
In this notebook shows how to fit a FRET histogram.
For a complete tutorial on burst anal... | Python Code:
from fretbursts import *
sns = init_notebook(apionly=True)
import lmfit
print('lmfit version:', lmfit.__version__)
# Tweak here matplotlib style
import matplotlib as mpl
mpl.rcParams['font.sans-serif'].insert(0, 'Arial')
mpl.rcParams['font.size'] = 12
%config InlineBackend.figure_format = 'retina'
Explanat... |
11,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Tensorboard in DeepChem
DeepChem Neural Networks models are built on top of tensorflow. Tensorboard is a powerful visualization tool in tensorflow for viewing your model architecture ... | Python Code:
from IPython.display import Image, display
import deepchem as dc
from deepchem.molnet import load_tox21
from deepchem.models.tensorgraph.models.graph_models import GraphConvModel
# Load Tox21 dataset
tox21_tasks, tox21_datasets, transformers = load_tox21(featurizer='GraphConv')
train_dataset, valid_dataset... |
11,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
网络科学理论
网络科学简介
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Directed
Links
Step2: <img src = './img/networks.png' width = 1000>
Degree, Average Degree and Degree Distribution
Step3: Undi... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import networkx as nx
Gu = nx.Graph()
for i, j in [(1, 2), (1, 4), (4, 2), (4, 3)]:
Gu.add_edge(i,j)
nx.draw(Gu, with_labels = True)
Explanation: 网络科学理论
网络科学简介
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
FROM SADDAM HUSSEI... |
11,878 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have been struggling with removing the time zone info from a column in a pandas dataframe. I have checked the following question, but it does not work for me: | Problem:
import pandas as pd
df = pd.DataFrame({'datetime': ['2015-12-01 00:00:00-06:00', '2015-12-02 00:01:00-06:00', '2015-12-03 00:00:00-06:00']})
df['datetime'] = pd.to_datetime(df['datetime'])
df['datetime'] = df['datetime'].dt.tz_localize(None)
df.sort_values(by='datetime', inplace=True)
df['datetime'] = df['date... |
11,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI Model Monitoring with Explainable AI Feature Attributions
<table align="left">
<td>
<a href="https
Step1: Set up your Google Cloud project
The following steps are required, ... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
import... |
11,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, notebook style sheet by L.A. Barba, N.C. Clementi
Step1: Numerical stabili... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, note... |
11,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to debug a model
There are various levels on which to debug a model. One of the simplest is to just print out the values that different variables are taking on.
Because PyMC3 uses Theano... | Python Code:
%matplotlib inline
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import theano.tensor as T
x = np.random.randn(100)
with pm.Model() as model:
mu = pm.Normal('mu', mu=0, sd=1)
sd = pm.Normal('sd', mu=0, sd=1)
obs = pm.Normal('obs'... |
11,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Understanding the use of the Merkle-Patricia tree in Ethereum
Ethereum innovated when designing their blockchain, in many ways when compared to Bitcoin. One of them was my enhancing the kind... | Python Code:
from trie import HexaryTrie
Explanation: Understanding the use of the Merkle-Patricia tree in Ethereum
Ethereum innovated when designing their blockchain, in many ways when compared to Bitcoin. One of them was my enhancing the kind of Merkle tree used within the blocks and how they are used.
In Ethereum, i... |
11,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quiver plots based on topographic aspect
Disclaimer
Step2: Note that we are setting the origin of the arrow (x_pos and y_pos) and then the direction (x_direct and y_direct) as coordinate p... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
def single_quiver(x_pos,y_pos,x_direct,y_direct, title=''):
fig, ax = plt.subplots()
ax.quiver(x_pos,y_pos,x_direct,y_direct, scale=5)
ax.axis([-2,2,-2,2])
if title !='':
plt.title(title)
plt.show()
#Aspect example: If it was 90 deg, that would... |
11,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading the data
Step1: Build clustering model
Here we build a kmeans model , and select the "optimal" of clusters.
Here we see that the optimal number of clusters is 2.
Step2: Build the o... | Python Code:
def loadContributions(file, withsexe=False):
contributions = pd.read_json(path_or_buf=file, orient="columns")
rows = [];
rindex = [];
for i in range(0, contributions.shape[0]):
row = {};
row['id'] = contributions['id'][i]
rindex.append(contributions['id'][i])
... |
11,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced plotting
This tutorial will go over more advanced plotting functionality. Before reading this, you should take a look at the basic analysis and plotting tutorial. First, we'll load... | Python Code:
import quail
%matplotlib inline
egg = quail.load_example_data()
Explanation: Advanced plotting
This tutorial will go over more advanced plotting functionality. Before reading this, you should take a look at the basic analysis and plotting tutorial. First, we'll load in some example data. This dataset is a... |
11,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Map, Filter, and Reduce Functions
https
Step2: filter function is used to select certain pieces of data from a list/tuple or other collection of data.
Step3: reduce | Python Code:
# 计算一系列半径的圆的面积
import math
# 计算面积
def area(r):
area of a circle with radius 'r'.
return math.pi * (r**2)
# 半径
radii = [2, 5, 7,1 ,0.3, 10]
# method 1
areas = []
for r in radii:
a = area(r)
areas.append(a)
areas
# method 2
[area(r) for r in radii]
# method 3, with map function, map take 2 ar... |
11,887 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 3
Imports
Step2: Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 3
Imports
End of explanation
def soliton(x, t, c, a):
#Return phi(x, t) for a soliton wave with con... |
11,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
Step1: In the following cell, complete the code with an expression that evaluates to a list of integers derived from the raw numbers in numbers_str, assigning the value of this expres... | Python Code:
numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'
Explanation: Grade: 10 / 11
Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1: List slices and list comprehensions
Let's start with some data. The... |
11,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PP2P protocol
By Roman Sasik (rsasik@ucsd.edu)
This Notebook describes the steps used in Gene Ontology analysis, which produces both conditional and unconditional posterior probabilities th... | Python Code:
!gfortran -ffree-line-length-none PP2p_branch_conditional_exact_pvalues.f90
!ls
Explanation: PP2P protocol
By Roman Sasik (rsasik@ucsd.edu)
This Notebook describes the steps used in Gene Ontology analysis, which produces both conditional and unconditional posterior probabilities that a GO term is differen... |
11,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="right">Python 3.6 Jupyter Notebook</div>
Introduction to Bandicoot
Your completion of the notebook exercises will be graded based on your ability to do the following
Step1: 1. D... | Python Code:
import os
import pandas as pd
import bandicoot as bc
import numpy as np
import matplotlib
Explanation: <div align="right">Python 3.6 Jupyter Notebook</div>
Introduction to Bandicoot
Your completion of the notebook exercises will be graded based on your ability to do the following:
Understand: Do your pseud... |
11,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ARTICLE CLUSTERS
Cluster Inertia
Cluster article data and compute inertia as a function of cluster number
Step1: Silhouette Score
Cluster article data and compute the silhouette score as a ... | Python Code:
from sklearn import cluster
import pandas as pd
import numpy as np
import pickle
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
num_topics = 20
doc_data = pickle.load(open('pub_probabs_topic'+str(num_topics)+'.pkl','rb'))
lda_topics = ['topic'+str(i) for i in range(0,num_topics)]
... |
11,892 | Given the following text description, write Python code to implement the functionality described.
Description:
Tribonacci Numbers
Program to print first n tribonacci numbers Matrix Multiplication function for 3 * 3 matrix ; Recursive function to raise the matrix T to the power n ; base condition . ; recursively call to... | Python Code:
def multiply(T , M ) :
a =(T[0 ][0 ] * M[0 ][0 ] + T[0 ][1 ] * M[1 ][0 ] + T[0 ][2 ] * M[2 ][0 ] )
b =(T[0 ][0 ] * M[0 ][1 ] + T[0 ][1 ] * M[1 ][1 ] + T[0 ][2 ] * M[2 ][1 ] )
c =(T[0 ][0 ] * M[0 ][2 ] + T[0 ][1 ] * M[1 ][2 ] + T[0 ][2 ] * M[2 ][2 ] )
d =(T[1 ][0 ] * M[0 ][0 ] + T[1 ][1 ] * M[1 ][0... |
11,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Lesson
Step2: Project 1
Step5: Transforming Text into Numbers | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
11,894 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature Engineering for Time Series Problems
Time series forecasting consists of predicting future values of a target using earlier observations. In datasets that are used in time series pro... | Python Code:
es = load_weather()
es['temperatures'].head(10)
es['temperatures']['Temp'].plot(ylabel='Temp (C)')
Explanation: Feature Engineering for Time Series Problems
Time series forecasting consists of predicting future values of a target using earlier observations. In datasets that are used in time series problems... |
11,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Micromagnetic standard problem 4
Author
Step1: We set all the necessary simulation parameters.
Step2: First stage
In the first stage, we relax the system at zero external magnetic field.
R... | Python Code:
!rm -rf standard_problem4/
Explanation: Micromagnetic standard problem 4
Author: Marijan Beg
Date: 11 May 2016
Problem specification
The simulated sample is a thin film cuboid with dimensions:
- length $L_{x} = 500 \,\text{nm}$,
- width $L_{y} = 125 \,\text{nm}$, and
- thickness $t = 3 \,\text{nm}$.
The ma... |
11,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2 - Getting started with SampleData
Step1: Before starting to create our datasets, we will take a look at the SampleData class documenation, to discover the arguments of the class construc... | Python Code:
from pymicro.core.samples import SampleData as SD
Explanation: 2 - Getting started with SampleData : Exploring dataset contents
This second User Guide tutorial will introduce you to:
create and open datasets with the SampleData class
the SampleData Naming System
how to get informations on a dataset content... |
11,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to optimization
The basic components
The objective function (also called the 'cost' function)
Step1: The "optimizer"
Step2: Additional components
"Box" constraints
Step3: The... | Python Code:
import numpy as np
objective = np.poly1d([1.3, 4.0, 0.6])
print objective
Explanation: Introduction to optimization
The basic components
The objective function (also called the 'cost' function)
End of explanation
import scipy.optimize as opt
x_ = opt.fmin(objective, [3])
print "solved: x={}".format(x_)
%ma... |
11,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Two coupled equilibria
Step1: First, let's define our substances. ChemPy can parse chemical formulae into chempy.Substance instances with information on charge, composition, molar mass (and... | Python Code:
from operator import mul
from functools import reduce
from itertools import product
import chempy
from chempy.chemistry import Species, Equilibrium
from chempy.equilibria import EqSystem, NumSysLog, NumSysLin
import numpy as np
import sympy as sp
sp.init_printing()
import matplotlib.pyplot as plt
%matplotl... |
11,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Automatically 'discovering' the heat equation with reverse finite differencing
<a href="https
Step3: Okay, so now that we have our data to work on, we need to form a system of equati... | Python Code:
import numpy as np
from numpy.testing import assert_almost_equal
# Specify diffusion coefficient
nu = 0.1
def analytical_soln(xmax=1.0, tmax=0.2, nx=1000, nt=1000):
Compute analytical solution.
x = np.linspace(0, xmax, num=nx)
t = np.linspace(0, tmax, num=nt)
u = np.zeros((len(t), len(x))) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.