Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
1,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is the <a href="https
Step1: How do we define direction of an earth magnetic field?
Earth magnetic field is a vector. To define a vector we need to choose a coordinate system. We use r... | Python Code:
import numpy as np
from geoscilabs.mag import Mag, Simulator
%matplotlib inline
Explanation: This is the <a href="https://jupyter.org/">Jupyter Notebook</a>, an interactive coding and computation environment. For this lab, you do not have to write any code, you will only be running it.
To use the notebook... |
1,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How many tweets are about the 'wall'?
Step1: What is the average twitter tenure of people who tweeted about the wall?
Step2: There are a couple of users tweeting multiple times, but most t... | Python Code:
# Lowercase the hashtags and tweet body
df['hashtags'] = df['hashtags'].str.lower()
df['text'] = df['text'].str.lower()
print("Total number of tweets containing hashtag 'wall' = {}".format(len(df[df['hashtags'].str.contains('wall')])))
print("Total number of tweets whose body contains 'wall' = {}".format(l... |
1,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We're wasting a bunch of time waiting for our iterators to produce minibatches when we're running epochs. Seems like we should probably precompute them while the minibatch is being run on th... | Python Code:
import multiprocessing
import numpy as np
p = multiprocessing.Pool(4)
x = range(3)
f = lambda x: x*2
def f(x):
return x**2
print(x)
Explanation: We're wasting a bunch of time waiting for our iterators to produce minibatches when we're running epochs. Seems like we should probably precompute them while ... |
1,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intialize a spark instance-
Step1: Get number of RDD partitions-
Step2: We will define a square function for our map operation-
Step3: The above map function maps generated two types of k... | Python Code:
sc = pyspark.SparkContext(appName="spark-notebook")
ss = SparkSession(sc)
myRDD = sc.textFile("file:///path/to/part3/numbers.txt", 10)
Explanation: Intialize a spark instance-
End of explanation
myRDD.getNumPartitions()
print myRDD.take(20) # get first 20 values
Explanation: Get number of RDD partitions-
E... |
1,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Observation and clean of the data
Step1: 1.1. Missing values
Step2: Where are the missing values ?
Step3: To clean the data, we will go step by step
Step4: Check now how many incomple... | Python Code:
print('Number of diad: ', len(data))
print('Number of players: ', len(data.playerShort.unique()))
print('Number of referees: ', len(data.refNum.unique()))
Explanation: 1. Observation and clean of the data
End of explanation
complete = len(data.dropna())
all_ = len(data_total)
print('Number of row with comp... |
1,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Primer Design
One of the first things anyone learns in a molecular biology lab is how to design primers. The exact strategies vary a lot and are sometimes polymerase-specific. coral uses the... | Python Code:
import coral as cor
Explanation: Primer Design
One of the first things anyone learns in a molecular biology lab is how to design primers. The exact strategies vary a lot and are sometimes polymerase-specific. coral uses the Klavins' lab approach of targeting a specific melting temperature (Tm) and nothing ... |
1,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocess data
Step1: Conversion and cleaning
Surprise forces you to use schema ["user_id", "doc_id", "rating"]
CF models are often sensitive to NA values -> replace NaN with 0 (TBD
Step2:... | Python Code:
# Import data
path = "../data/petdata_1000_100.csv"
raw_data = pd.read_csv(path, index_col="doc_uri")
assert raw_data.shape == (1000,100), "Import error, df has false shape"
Explanation: Preprocess data
End of explanation
# Convert df
data = raw_data.unstack().to_frame().reset_index()
data.columns = ["user... |
1,107 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Tuning XGBoost Hyperparameters with Grid Search
| Python Code::
from sklearn.model_selection import GridSearchCV
import xgboost as xgb
# create a dictionary containing the hyperparameters
# to tune and the range of values to try
PARAMETERS = {"subsample":[0.75, 1],
"colsample_bytree":[0.75, 1],
"max_depth":[2, 6],
"min_child_w... |
1,108 | 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" style="margin-top
Step1: Because the Seasons 2 and 3 together only use about 1.7 GB of RAM, no need of special on-di... | Python Code:
import planet4 as p4
import pandas as pd
from planet4 import io
db = io.DBManager()
db_fname = db.dbname
db.dbname
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc" style="margin-top: 1em;"><ul class="toc-item"><li><span><a href="#Task:-Define-status-of-Planet-4" data-to... |
1,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WMI Win32_Process Class and Create Method for Remote Execution
Metadata
| | |
|
Step1: Download & Process Mordor Dataset
Step2: Analytic I
Look for wmiprvse.exe spawni... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: WMI Win32_Process Class and Create Method for Remote Execution
Metadata
| | |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/10 |
| modification date |... |
1,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Structures
Data structures are a concrete implementation of the specification provided by one or more particular abstract data types (ADT), which specify the operations that can be perf... | Python Code:
from openanalysis.data_structures import DataStructureBase, DataStructureVisualization
import gi.repository.Gtk as gtk # for displaying GUI dialogs
Explanation: Data Structures
Data structures are a concrete implementation of the specification provided by one or more particular abstract data types (ADT),... |
1,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing a LexisNexus text export into CSV
Preparation
download the file
Step1: Show the number of characters in the text file
Step2: Downloading the text file directly from github using... | Python Code:
text = open('data/LexisNexusVapingExample.txt', 'r').read()
Explanation: Processing a LexisNexus text export into CSV
Preparation
download the file: https://github.com/mbod/intro_python_for_comm/blob/master/data/LexisNexusVapingExample.txt
place it in the data folder of your IPython notebook
Task
Load the ... |
1,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fixed and Random Effect Models
Step1: Exploring Within-Group Variation and Between-Group Variation
Multilevel models make sense in cases where we might expect there to be variation between ... | Python Code:
# THINGS TO IMPORT
# This is a baseline set of libraries I import by default if I'm rushed for time.
%matplotlib inline
import codecs # load UTF-8 Content
import json # load JSON files
import pandas as pd # Pandas handles dataframes
import numpy as np... |
1,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Since we announced our collaboration with the World Bank and more partners to create the Open Traffic platform, we’ve been busy. We’ve shared two technical previews of the OSMLR linear refer... | Python Code:
import os
import sys; sys.path.insert(0, os.path.abspath('..'));
import validator.validator as val
import numpy as np
import glob
import pandas as pd
import pickle
import seaborn as sns
from matplotlib import pyplot as plt
from IPython.display import Image
from IPython.core.display import HTML
%matplotlib... |
1,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hodograph Inset
Layout a Skew-T plot with a hodograph inset into the plot.
Step1: Upper air data can be obtained using the siphon package, but for this example we will use
some of MetPy's s... | Python Code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import numpy as np
import pandas as pd
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, Hodograph, SkewT
from metpy.units import units
Explanation: Hodograph... |
1,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 4 - Inferences with Gaussians
4.1 Inferring a mean and standard deviation
Inferring the mean and variance of a Gaussian distribution.
$$ \mu \sim \text{Gaussian}(0, .001) $$
$$ \si... | Python Code:
# Data
x = np.array([1.1, 1.9, 2.3, 1.8])
n = len(x)
with pm.Model() as model1:
# prior
mu = pm.Normal('mu', mu=0, tau=.001)
sigma = pm.Uniform('sigma', lower=0, upper=10)
# observed
xi = pm.Normal('xi',mu=mu, tau=1/(sigma**2), observed=x)
# inference
trace = pm.sample(1e3,... |
1,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Method 1
Step2: Method 2 | Python Code:
# Import modules
import pandas as pd
import numpy as np
# Create a dataframe
raw_data = {'first_name': ['Jason', 'Molly', np.nan, np.nan, np.nan],
'nationality': ['USA', 'USA', 'France', 'UK', 'UK'],
'age': [42, 52, 36, 24, 70]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'nation... |
1,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick start
Open this page in an interactive mode via Google Colaboratory.
In this quick starting guide we show the basics of working with t3f library. The main concept of the library is a T... | Python Code:
import numpy as np
# Import TF 2.
%tensorflow_version 2.x
import tensorflow as tf
# Fix seed so that the results are reproducable.
tf.random.set_seed(0)
np.random.seed(0)
try:
import t3f
except ImportError:
# Install T3F if it's not already installed.
!git clone https://github.com/Bihaqo/t3f.gi... |
1,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Delaunay
Here, we'll perform various analysis by constructing graphs and measure properties of those graphs to learn more about the data
Step1: We'll start with just looking at analysis in ... | Python Code:
import csv
from scipy.stats import kurtosis
from scipy.stats import skew
from scipy.spatial import Delaunay
import numpy as np
import math
import skimage
import matplotlib.pyplot as plt
import seaborn as sns
from skimage import future
import networkx as nx
from ragGen import *
%matplotlib inline
sns.set_co... |
1,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Recommending movies
Step2: Preparing the dataset
Next, we need to prepare our dataset. We are going to leverage the data generation utility in... | 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... |
1,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Leemos los sondeos obtenidos de la wikipedia (https
Step1: Hacemos un dibujo con los datos. Cada valor del sondeo se muestra con puntos. Además hacemos una regresión con un Gaussian Process... | Python Code:
book = xlrd.open_workbook("sondeos.xlsx")
sh = book.sheet_by_index(0)
PP = []
PSOE = []
IU = []
UPyD = []
Podemos = []
Ciudadanos = []
fecha = []
mesEsp = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']
mesEng = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', '... |
1,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dev for Handling BAM Extaction Radii
Step1: NOTE that in the case below, r6.l6 us loaded while r5.l5 is the config file default. This is the desired behavior as there is not r5.l5 for this ... | Python Code:
# Setup ipython environment
%load_ext autoreload
%autoreload 2
# %matplotlib auto
%matplotlib inline
# Import useful things
from nrutils import scsearch,gwylm
# Setup plotting backend
import matplotlib as mpl
from mpl_toolkits.mplot3d import axes3d
mpl.rcParams['lines.linewidth'] = 0.8
mpl.rcParams['font.f... |
1,122 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have been trying to get the arithmetic result of a lognormal distribution using Scipy. I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be ... | Problem:
import numpy as np
from scipy import stats
stddev = 2.0785
mu = 1.744
expected_value = np.exp(mu + stddev ** 2 / 2)
median = np.exp(mu) |
1,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Definition(s)
The closest pair of points problem or closest pair problem is a problem of computational geometry
Step1: Naive implementation of closest_pair
Step2: Draw points (with closest... | Python Code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from operator import itemgetter
%matplotlib inline
def euclid_distance(p, q):
return np.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
def search(points, st, dr):
if st >= dr:
return np.inf, None, None
elif st + 1 == dr... |
1,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instructions
Compute the sample statistics on the given data using numpy. Write the equation in LaTeX first and then complete the computation in Python second. You may refer to equations in ... | Python Code:
#example
example_data_do_not_use = [4,3,6,3]
print(sum(example_data_do_not_use))
Explanation: Instructions
Compute the sample statistics on the given data using numpy. Write the equation in LaTeX first and then complete the computation in Python second. You may refer to equations in other problems. For exa... |
1,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nerc', 'hadgem3-gc31-hh', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NERC
Source ID: HADGEM3-GC31-HH
Topic: Aerosol
Sub-Topics: Transpor... |
1,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of two oyster samples where Lotterhos did methylRAD
The M2 and M3 samples are here
Step1: Genome version
Step2: Products | Python Code:
bsmaploc="/Applications/bioinfo/BSMAP/bsmap-2.74/"
Explanation: Analysis of two oyster samples where Lotterhos did methylRAD
The M2 and M3 samples are here:
http://owl.fish.washington.edu/nightingales/C_gigas/9_GATCAG_L001_R1_001.fastq.gz
http://owl.fish.washington.edu/nightingales/C_gigas/10_TAGCTT_L001_R... |
1,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The Cirq Developers
Step1: Custom gates
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: Standard gates such as Pauli gates... | 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... |
1,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Channels
Channel
A Channel gives a means of asynchronous iteration over items coming from some upstream source.
A consumer of a Channel uses its next() method to iteratively ... | Python Code:
def print_chans(*chans):
app.Flo([chan.map(print) for chan in chans]).run()
Explanation: Introduction to Channels
Channel
A Channel gives a means of asynchronous iteration over items coming from some upstream source.
A consumer of a Channel uses its next() method to iteratively receive items as the cha... |
1,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
关于分辨率
先扫一下盲:http
Step1: 两种情况
把resize的image保存到和原image同一目录下
http
Step2: 把resize的image保存到同一目录下
另外为了保存到和原image同一目录下,我们要
os.path.split(path)
将path分割成目录和文件名二元组返回。
```
os.path.split('c | Python Code:
import os
import glob
from PIL import Image
def thumbnail_pic(path):
a = glob.glob(r'*.jpg')
for x in a:
name = os.path.join(path, x)
im = Image.open(name)
im.thumbnail((1136, 640))
print(im.format, im.size, im.mode)
im.save(name, 'JPEG')
print('Done!')
i... |
1,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize subject head movement
Show how subjects move as a function of time.
Step1: Visualize the subject head movements as traces
Step2: Or we can visualize them as a continuous field (w... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
from os import path as op
import mne
print(__doc__)
data_path = op.join(mne.datasets.testing.data_path(verbose=True), 'SSS')
pos = mne.chpi.read_head_pos(op.join(data_path, 'test_move_anon_raw.pos'))
Explanation: Visualize subject... |
1,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Process Regression and Classification with Elliptical Slice Sampling
Elliptical slice sampling is a variant of slice sampling that allows sampling from distributions with multivaria... | Python Code:
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import theano.tensor as tt
sns.set(style='white', palette='deep', color_codes=True)
%matplotlib inline
Explanation: Gaussian Process Regression and Classification with Elliptical Slice Sampling
Elliptical slice samp... |
1,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 07 - Non linear Elliptic problem
Keywords
Step1: 3. Affine Decomposition
For this problem the affine decomposition is straightforward
Step2: 4. Main program
4.1. Read the mesh for... | Python Code:
from dolfin import *
from rbnics import *
Explanation: Tutorial 07 - Non linear Elliptic problem
Keywords: DEIM, POD-Galerkin
1. Introduction
In this tutorial, we consider a non linear elliptic problem in a two-dimensional spatial domain $\Omega=(0,1)^2$. We impose a homogeneous Dirichlet condition on the ... |
1,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 id="tocheading">Table of Contents</h1>
<div id="toc"></div>
Step1: DataFrame basics
Difficulty
Step2: Task
Step3: Task
Step4: Task
Step5: Task
Step6: Task
Step7: Task
Step8: Task... | Python Code:
%%javascript
$.getScript('misc/kmahelona_ipython_notebook_toc.js')
Explanation: <h1 id="tocheading">Table of Contents</h1>
<div id="toc"></div>
End of explanation
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np... |
1,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using side features
Step1: Please re-run the above cell if you are getting any incompatible warnings and errors.
Step2: There are a couple of key features here
Step3: The layer itself doe... | Python Code:
!pip install -q --upgrade tensorflow-datasets
Explanation: Using side features: feature preprocessing
Learning Objectives
Turning categorical features into embeddings.
Normalizing continuous features.
Processing text features.
Build a User and Movie model.
Introduction
One of the great advantages of using ... |
1,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gradient Boosted Models
Gradient Boosting does not refer to one particular model, but a versatile framework to optimize many loss functions. It follows the strength in numbers principle by c... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
from sklearn.model_selection import train_test_split
from sksurv.datasets import load_breast_cancer
from sksurv.ensemble import ComponentwiseGradientBoostingSurvivalAnalysis
from sksurv.ensemble import GradientBoostin... |
1,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
At the end of this lesson, you will be able to write TensorFlow and Keras code to use one of the best models in computer vision.
Lesson
Step1: Sample Code
Choose Images to Work With
S... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('sDG5tPtsbSA', width=800, height=450)
Explanation: Intro
At the end of this lesson, you will be able to write TensorFlow and Keras code to use one of the best models in computer vision.
Lesson
End of explanation
from os.path import join
image_dir = '../... |
1,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of MCE IRL code & environments
This is just tabular environments & vanilla MCE IRL.
Step1: IRL on a random MDP
Testing both linear reward models & MLP reward models.
Step2: S... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import copy
import numpy as np
import seaborn as sns
import pandas as pd
import jax.experimental.optimizers as jaxopt
import matplotlib.pyplot as plt
import scipy
import imitation.tabular_irl as tirl
import imitation.examples.model_envs as menv
sns.set(... |
1,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-2', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-2
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
1,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyMCEF Quickstart tutorial
<br>
<br>
Prerequisites
Install
Please install package PyMCEF through either conda or pip
Step1: Instead of smoothing, we directly exclude those stocks with extre... | Python Code:
import pandas as pd
returns = pd.read_json('data/Russel3k_return.json')
Explanation: PyMCEF Quickstart tutorial
<br>
<br>
Prerequisites
Install
Please install package PyMCEF through either conda or pip:
<pre>
$ conda install -c hzzyyy pymcef
$ pip install pymcef
</pre>
conda packages are available on anaco... |
1,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optimization Exercise 1
Imports
Step1: Hat potential
The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Optimization Exercise 1
Imports
End of explanation
# YOUR CODE HERE
def hat(x, a, b):
return (-a * x**2) + (b * x**4)
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(... |
1,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contents
Introduction
Block Using the Sorted Neighborhood Blocker
Block Tables to Produce a Candidate Set of Tuple Pairs
Handling Missing Values
Window Size
Stable Sort Order
Sorted Neighbor... | Python Code:
# Import py_entitymatching package
import py_entitymatching as em
import os
import pandas as pd
Explanation: Contents
Introduction
Block Using the Sorted Neighborhood Blocker
Block Tables to Produce a Candidate Set of Tuple Pairs
Handling Missing Values
Window Size
Stable Sort Order
Sorted Neighborhood Blo... |
1,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot a univariate distribution along the x axis
Step1: Flip the plot by assigning the data variable to the y axis
Step2: Plot distributions for each column of a wide-form dataset
Step3: U... | Python Code:
tips = sns.load_dataset("tips")
sns.kdeplot(data=tips, x="total_bill")
Explanation: Plot a univariate distribution along the x axis:
End of explanation
sns.kdeplot(data=tips, y="total_bill")
Explanation: Flip the plot by assigning the data variable to the y axis:
End of explanation
iris = sns.load_dataset(... |
1,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A/B Testing with Hierarchical Models
Though A/B testing seems simple in that you're just comparing A against B and see which one performs better, but figuring out whether your results mean a... | Python Code:
# Website A had 1055 clicks and 28 sign-ups
# Website B had 1057 clicks and 45 sign-ups
values_A = np.hstack( ( [0] * (1055 - 28), [1] * 28 ) )
values_B = np.hstack( ( [0] * (1057 - 45), [1] * 45 ) )
print(values_A)
print(values_B)
Explanation: A/B Testing with Hierarchical Models
Though A/B testing seem... |
1,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Run this cell to set everything up!
Step1: In the next two questions, you'll create a boosted hybrid for the Store Sales dataset by implementing a new Python class. Run this ce... | Python Code:
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.time_series.ex5 import *
# Setup notebook
from pathlib import Path
from learntools.time_series.style import * # plot style settings
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_mode... |
1,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: tf.summary の使用箇所を TF 2.0 に移行する
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: TensorFlow 2... | 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... |
1,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create The Data
The dataset used in this tutorial is the famous iris dataset. The Iris target data contains 50 samples from three species of Iris, y and four feature variables,... | Python Code:
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
Explanation: Title: Logistic Regression With L1 Regularization
Slug: logistic_regression_with_l1_regulari... |
1,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dirichlet distribution
https
Step1: Setting up the Code
Before we can plot our Dirichlet distributions, we need to do three things
Step2: Gamma | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
from functools import reduce
# import seaborn
from math import gamma
from operator import mul
corners = np.array([[0, 0], [1, 0], [0.5,0.75**0.5]])
print(corners)
triangle = tri.Triangulation(corners[:, 0], c... |
1,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Environment Preparation
Install Java 8
Run the cell on the Google Colab to install jdk 1.8.
Note
Step2: Install BigDL Orca
Conda is needed to prepare the Python envir... | 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
1,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Configuring MNE python
This tutorial gives a short introduction to MNE configurations.
Step1: MNE-python stores configurations to a folder called .mne in the user's
home directory, or to Ap... | Python Code:
import os.path as op
import mne
from mne.datasets.sample import data_path
fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO')
Explanation: Configuring MNE python
This tutorial gives ... |
1,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple SEA model of two rooms with a dividing wall
In this notebook we create a simple SEA model of two rooms divided by a concrete wall.
We start by importing some of the modules that are... | Python Code:
import numpy as np
import pandas as pd
pd.set_option('float_format', '{:.2e}'.format)
import matplotlib
%matplotlib inline
Explanation: A simple SEA model of two rooms with a dividing wall
In this notebook we create a simple SEA model of two rooms divided by a concrete wall.
We start by importing some of t... |
1,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 理解语言的 Transformer 模型
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: 设置输入流水线(input pipeline... | 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... |
1,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
데이터 파일 읽고 쓰기
특정 파일을 열어 저장된 데이터를 읽거나 특정 데이터를 특정 파일에 저장해야 하는 일이 매우 빈번하게 발생한다.
파일을 열어 저장된 데이터 읽기
읽은 데이터 다루기
Step1: open 함수는 지정된 파일명을 가진 파일을 생성하고 파일의 위치를 리턴한다.
'w' 인자는 쓰기 전용으로 파일을 생성한다는 의미이며 모드... | Python Code:
ls
f = open('test.txt', 'w')
Explanation: 데이터 파일 읽고 쓰기
특정 파일을 열어 저장된 데이터를 읽거나 특정 데이터를 특정 파일에 저장해야 하는 일이 매우 빈번하게 발생한다.
파일을 열어 저장된 데이터 읽기
읽은 데이터 다루기: 계산, 필터링 등등
다룬 결과를 특정 파일에 저장하기
상황 설정: 마트에서 장보기
마트에서 장을 보기 위해 상품 목록을 미리 작성하여 가격을 확인한다.
품목 개수 단가
-----------------
빵 1개 1.39
토마토 6개 0.26
우유 3개 ... |
1,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Process inference in PyMC3
This is the first step in modelling Species occurrence.
The good news is that MCMC works,
The bad one is that it's computationally intense.
Step1: Simul... | Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps/external_plugins/spystats/')
import django
django.setup()
import pandas as pd
import matplotlib.pyplot as plt
## Use the ggplot style
plt.style.use('ggplot')
import numpy as np
from spystats import tools
Explanation: Ga... |
1,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dead time corrections
Daniel FY, Jeffrey AF. Mean and variance of single photon counting with deadtime. Physics in Medicine & Biology. 2000;45(7)
Step1: Equation 2 gives the expectation and... | Python Code:
%matplotlib inline
from pprint import pprint
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc3 as mc
import spacepy.toolbox as tb
import spacepy.plot as spp
import tqdm
from scipy import stats
import seaborn as sns
sns.set(font_scale=1.5)
# matplotlib.pyp... |
1,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-armed bandit as a Markov decision process
Let's model the Bernouilli multi-armed bandit. The Bernoulli MBA is an $N$-armed bandit where each arm gives binary rewards according to some ... | Python Code:
import itertools
import numpy as np
from pprint import pprint
def sorted_values(dict_):
return [dict_[x] for x in sorted(dict_)]
def solve_bmab_value_iteration(N_arms, M_trials, gamma=1,
max_iter=10, conv_crit = .01):
util = {}
# Initialize every state to uti... |
1,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Flower Dataset
Step2: Standardize Features
Step3: Create Logistic Regression
Step4: Train Logistic Regression
Step5: Create Previously Unseen Observation
Step6: ... | Python Code:
# Load libraries
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
Explanation: Title: Logistic Regression
Slug: logistic_regression
Summary: How to train a logistic regression in scikit-learn.
Date: 2017-09-21 12:00
Category: ... |
1,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 첫 번째 신경망 훈련하기
Step2: 패션 MNIST 데이터셋 임포트하기
10개의 범주(category)와 70,000개의 흑백 이미지로 구성된 패션 MNIST 데이터셋을 사용하겠습니다. 이미지는 해상도(28x28 픽셀)가 낮고 다음처럼 개별 옷 품목을 ... | 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... |
1,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maskbits QA in dr8c
Step1: Check the masking
Step2: All DUPs should be in an LSLGA blob.
Step3: 1) Find all bright Gaia stars.
2) Make sure the magnitude limits are correct.
3) Make sure ... | Python Code:
import os, time
import numpy as np
import fitsio
from glob import glob
import matplotlib.pyplot as plt
from astropy.table import vstack, Table, hstack
Explanation: Maskbits QA in dr8c
End of explanation
MASKBITS = dict(
NPRIMARY = 0x1, # not PRIMARY
BRIGHT = 0x2,
SATUR_G = 0x4,
S... |
1,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
whatever-forever
Create reusable, higher-order functions using declarative syntaxes in Python.
Installation
pip install whatever-forever
Basic Usage
Chaining <small>in Python</small>
Step1: ... | Python Code:
from whatever import *
__my_chain = __x(5).range.map(lambda x: x+3).list
__my_chain
Explanation: whatever-forever
Create reusable, higher-order functions using declarative syntaxes in Python.
Installation
pip install whatever-forever
Basic Usage
Chaining <small>in Python</small>
End of explanation
from ran... |
1,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot multiple volcanic data sets from the FITS (FIeld Time Series) database
In this notebook we will plot data of multiple types from volcano observatory instruments using data from the FITS... | Python Code:
# Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Define functions
def build_query(site, data_type):
'''
Take site code and data type and generate a FITS API query for an observations csv file
'''
# Ensure parameters are in the correct form... |
1,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature importances with forests of trees
This examples shows the use of forests of trees to evaluate the importance of
features on an artificial classification task. The red bars are the fe... | Python Code:
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier
Explanation: Feature importances with forests of trees
This examples shows the use of forests of trees to evaluate the imp... |
1,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Traveling Salesman problem
Names of group members
// put your names here!
Goals of this assignment
The main goal of this assignment is to use Monte Carlo methods to find the shortest pat... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
def calc_total_distance(table_of_distances, city_order):
'''
Calculates distances between a sequence of cities.
Inputs: N x N table containing distances between each pair... |
1,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Following the theano Tutorial
Step1: Baby Steps - Algebra
Adding two Scalars
Step2: "Prefer constructors like matrix, vector and scalar to dmatrix, dvector and dscalar because the former w... | Python Code:
%matplotlib inline
from theano import *
import theano.tensor as T
Explanation: Following the theano Tutorial
End of explanation
import numpy
from theano import function
x = T.dscalar('x')
y = T.dscalar('y')
z = x+y
f = function([x,y],z)
print type(x), type(y), type(z), type(f) # good to know what these
... |
1,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iterative Maximum Likelihood Estimation (iMLE)
Shahnawaz Ahmed, Chalmers University of Technology, Sweden
Email
Step1: Displacement operation
The measurements for determining optical quantu... | Python Code:
# imports
import numpy as np
from qutip import Qobj, rand_dm, fidelity, displace, qdiags, qeye, expect
from qutip.states import coherent, coherent_dm, thermal_dm, fock_dm
from qutip.random_objects import rand_dm
from qutip.visualization import plot_wigner, hinton, plot_wigner_fock_distribution
from qutip.... |
1,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
1,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advent of Code 2017
December 1st
[Given] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit aft... | Python Code:
from notebook_preamble import J, V, define
Explanation: Advent of Code 2017
December 1st
[Given] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.
For example... |
1,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
1,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
======================================================================
Compute source power spectral density (PSD) of VectorView and OPM data
================================================... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Luke Bloy <luke.bloy@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
from mne.filter import next_fast_len
import mne
print(__doc__)
data_path = mne.datasets.opm.data_path()
subject =... |
1,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluating Services
Sentiment analysis plugins can also be evaluated on a series of pre-defined datasets.
This can be done in three ways
Step1: Programmatically (expert)
A third option is t... | Python Code:
import requests
from IPython.display import Code
endpoint = 'http://senpy.gsi.upm.es/api'
res = requests.get(f'{endpoint}/evaluate',
params={"algo": "sentiment-vader",
"dataset": "vader,sts",
'outformat': 'json-ld'
... |
1,170 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
In pandas, how do I replace & with '&' from all columns where & could be in any position in a string?Then please evaluate this expression. | Problem:
import pandas as pd
df = pd.DataFrame({'A': ['1 & 1', 'BB', 'CC', 'DD', '1 & 0'], 'B': range(5), 'C': ['0 & 0'] * 5})
def g(df):
for i in df.index:
for col in list(df):
if type(df.loc[i, col]) == str:
if '&' in df.loc[i, col]:
df.loc[i... |
1,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0.
RNN for Character Level Language Modelin... | Python Code:
from __future__ import division
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from builtins import range
from builtins import object
from past.utils import old_div
import pickle as pickle
import numpy as np
import argpa... |
1,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Предобработка данных и логистическая регрессия для задачи бинарной классификации
Programming assignment
В задании вам будет предложено ознакомиться с основными техниками предобработки данных... | Python Code:
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.style.use('ggplot')
%matplotlib inline
Explanation: Предобработка данных и логистическая регрессия для задачи бинарной классификации
Programming assignment
В задании вам будет предложено ознакомиться с ... |
1,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How data scientists use BigQuery
This notebook accompanies the presentation
"Machine Learning and Bayesian Statistics in minutes
Step1: But is it right, though? What's with the weird hump ... | Python Code:
%%bigquery df
WITH rawnumbers AS (
SELECT
departure_delay,
COUNT(1) AS num_flights,
COUNTIF(arrival_delay < 15) AS num_ontime
FROM
`bigquery-samples.airline_ontime_data.flights`
GROUP BY
departure_delay
HAVING
num_flights > 100
),
totals AS (
SELECT
SUM(num_flights) AS tot_flights,
SUM(nu... |
1,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyze and Report Current Plate
Analyze and report a Cell Painting screening plate in 384 format
Step1: Report Current Plate with Existing Data
Report a Cell Painting screening plate in 38... | Python Code:
DATE = "170530" # "170704", "170530"
PLATE = "SI0012"
CONF = "conf170511mpc" # "conf170623mpc", "conf170511mpc"
QUADRANTS = [1] # [1, 2, 3, 4]
WRITE_PKL = False
UPDATE_SIMILAR = False
UPDATE_DATASTORE = False
for quadrant in QUADRANTS:
SRC_DIR = ... |
1,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Symbulate Lab 1 - Probability Spaces
This Jupyter notebook provides a template for you to fill in. Complete the parts as indicated. To run a cell, hold down SHIFT and hit ENTER.
In this la... | Python Code:
from symbulate import *
%matplotlib inline
Explanation: Symbulate Lab 1 - Probability Spaces
This Jupyter notebook provides a template for you to fill in. Complete the parts as indicated. To run a cell, hold down SHIFT and hit ENTER.
In this lab you will use the Python package Symbulate. You should have... |
1,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate synthetic training data
The goal for this file is to generate some synthetic data for our sample model to train on.
Step1: Power ups
These are the power ups that are available to u... | Python Code:
import pandas as pd
import numpy as np
import random
Explanation: Generate synthetic training data
The goal for this file is to generate some synthetic data for our sample model to train on.
End of explanation
power_ups = ['time_machine', 'coin_magnet', 'coin_multiplier', 'sparky_armor', 'extra_life', 'hea... |
1,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Impedance Matching
Introduction
The general problem is illustrated by the figure below
Step1: Matching with Lumped Elements
To begin, let's assume that the matching network is lossless and ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import skrf as rf
rf.stylely()
Explanation: Impedance Matching
Introduction
The general problem is illustrated by the figure below: a generator with an internal impedance $Z_S$ delivers a power to a passive load $Z_L$, through a 2-ports matching network. T... |
1,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Atmospheres & Passbands
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 wan... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: Atmospheres & Passbands
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 in... |
1,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'mohc', 'sandbox-3', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: MOHC
Source ID: SANDBOX-3
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
1,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<style>
@font-face {
font-family
Step1: One nice feature of ipython notebooks is it's easy to make small changes to code and
then re-execute quickly, to see how things change. For examp... | Python Code:
import pandas as pd
features_df = pd.DataFrame.from_csv("well_data.csv")
labels_df = pd.DataFrame.from_csv("well_labels.csv")
print( labels_df.head() )
Explanation: <style>
@font-face {
font-family: CharisSILW;
src: url(files/CharisSIL-R.woff);
}
@font-face {
font-family: CharisSILW;
font-st... |
1,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mengukur Downside Risk dengan VaR dan CVaR
Seperti kita bahas dalam studi sebelumnya, distribusi dari keuntungan biasanya bukanlah normal, sehingga pemakaian standar deviasi kurang tepat kar... | Python Code:
import numpy as np
import pandas as pd
np.random.seed(0)
returns = pd.Series(np.random.normal(0, 0.10, 100)).sort_values()
returns.values
Explanation: Mengukur Downside Risk dengan VaR dan CVaR
Seperti kita bahas dalam studi sebelumnya, distribusi dari keuntungan biasanya bukanlah normal, sehingga pemakaia... |
1,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
E2.1 Shortest Paths and Cycles
Step1: a) How many nodes and edges does G have?
Step2: b) How many cycles does the cycle basis of the graph contain? How Many
edges does the longest cycle i... | Python Code:
G=nx.read_graphml("../data/visualization/small_graph.xml", node_type=int)#Load the graph
Explanation: E2.1 Shortest Paths and Cycles
End of explanation
nodes = G.number_of_nodes()
edges = G.number_of_edges()
print("b) The graph has %d nodes and %d edges\n"%(nodes,edges))
Explanation: a) How many nodes and... |
1,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clase 11
Step1: 2. Uso de Pandas para descargar datos de precios de cierre
Una vez cargados los paquetes, es necesario definir los tickers de las acciones que se usarán, la fuente de descar... | Python Code:
#importar los paquetes que se van a usar
import pandas as pd
import numpy as np
import datetime
from datetime import datetime
import scipy.stats as stats
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.covariance as skcov
import cvxopt as opt
from cvxopt import blas,... |
1,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find distribution of local maxima in a Gaussian Random Field
In this notebook, I evaluate different known distributions for local maxima in a Gaussian Random Field. I followed several steps... | Python Code:
% matplotlib inline
import os
import numpy as np
import nibabel as nib
from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset
import nipy.algorithms.statistics.rft as rft
from __future__ import print_function, division
import math
import matplotlib.pyplot as plt
import palettable.... |
1,185 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Input example: | Problem:
import numpy as np
a = np.array([[0, 1], [2, 1], [4, 8]])
mask = (a.min(axis=1,keepdims=1) == a) |
1,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Non-Linear Time History Analysis (NLTHA) on Single Degree of Freedom (SDOF) Oscillators
In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear t... | Python Code:
from rmtk.vulnerability.common import utils
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF import NLTHA_on_SDOF
from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF.read_pinching_parameters import read_parameters
%matplotlib inline
Explanation: Non-Linear Time History Analysis (NLTHA) on ... |
1,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HTML Introduction
Unit 17, Lecture 2
Numerical Methods and Statistics
Prof. Andrew White, April 21, 2016
Websites are made using three core technologies
Step1: Links
Step2: Content Arrange... | Python Code:
%%HTML
<h3> A level-3 (smaller) heading</h3>
<p> This is a paragraph about HTML. HTML surprisingly only has about 5 elements you need to know: </p>
<ul>
<li> Paragraphs</li>
<li> breaks </li>
<li> lists </li>
<li> links </li>
<li> images </li>
<li> divs <... |
1,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Suppose we want to access three different elements. We could do it like this
Step2: Alternatively, we can pass a singl... | Python Code:
import numpy as np
rand = np.random.RandomState(42)
x = rand.randint(100, size=10)
print(x)
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the ... |
1,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contrast Effects
Authors
Ndèye Gagnessiry Ndiaye and Christin Seifert
License
This work is licensed under the Creative Commons Attribution 3.0 Unported License https
Step1: The following im... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: Contrast Effects
Authors
Ndèye Gagnessiry Ndiaye and Christin Seifert
License
This work is licensed under the Creative Commons Attribution 3.0 Unported License https://creativecommons.org/licenses/by/3.0/
This notebook illustrates 3 contrast e... |
1,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation of a Noddy history and visualisation of output
This example shows how the module pynoddy.history can be used to compute the model, and how simple visualisations can be generated w... | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# Basic settings
import sys, os
import subprocess
sys.path.append("../..")
# Now import pynoddy
import pynoddy
import importlib
importlib.reload(pynoddy)
import pynoddy.output
import pynoddy.h... |
1,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Single Star with Spots
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
Step1: As... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Single Star with Spots
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import numpy as ... |
1,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to train a Keras model on TFRecord files
Author
Step1: We want a bigger batch size as our data is not balanced.
Step2: Load the data
Step3: Decoding the data
The images have to be con... | Python Code:
import tensorflow as tf
from functools import partial
import matplotlib.pyplot as plt
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()
print("Device:", tpu.master())
strategy = tf.distribute.TPUStrategy(tpu)
except:
strategy = tf.distribute.get_strategy()
print("Number... |
1,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this notebook, we will show you how to evaluate the levenshtein ration between the training phrases of two intents.
Prerequisites
Ensure you have a GCP Service Account key wi... | Python Code:
# If you haven't already, make sure you install the `dfcx-scrapi` library
!pip install dfcx-scrapi
Explanation: Introduction
In this notebook, we will show you how to evaluate the levenshtein ration between the training phrases of two intents.
Prerequisites
Ensure you have a GCP Service Account key with th... |
1,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyBroMo 4. Two-state dynamics - Static smFRET simulation
<small><i>
This notebook is part of <a href="http
Step1: Define populations
We assume a $\gamma = 0.7$ and two populations, one with... | Python Code:
%matplotlib inline
from pathlib import Path
import numpy as np
import tables
import matplotlib.pyplot as plt
import seaborn as sns
import pybromo as pbm
import phconvert as phc
print('Numpy version:', np.__version__)
print('PyTables version:', tables.__version__)
print('PyBroMo version:', pbm.__version__)
... |
1,195 | 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="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1 </span>Summary</a></div><div class="lev1 toc-item"... | Python Code:
%run ../../code/version_check.py
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1 </span>Summary</a></div><div class="lev1 toc-item"><a href="#Version-Control" data-toc-modified-id="Version-Control-2"><s... |
1,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graphing catalog numbers vs rank
Are collection codes typically sequential? Let's graph only numeric codes (can do work to conver alpha-numeric codes to based 10 numeric) vs their rank. If c... | Python Code:
import pyspark.sql.functions as sql
import pyspark.sql.types as types
idb_df_version = "20170130"
idb_df = sqlContext.read.parquet("/guoda/data/idigbio-{0}.parquet".format(idb_df_version))
idb_df.count()
Explanation: Graphing catalog numbers vs rank
Are collection codes typically sequential? Let's graph on... |
1,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Course Transcriptomics for Cu-Induced transition in 5GB1
Step1: Aside, how to keep only columns with FM40, and FM34
Step2: identifying the column index in order to remove unnecessary ... | Python Code:
import pandas as pd
import natsort as ns #3rd party package for natural sorting
import re
data = pd.read_csv("5G_counts.tsv", sep = "\t")
columns_list = list(range(0,9)) + list(range(20,42)) #creating a list of columns that I care about (see below)
data_1 = data.iloc[:, columns_list] #taking only 0-8 and ... |
1,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Discretizations
Here we show how different discretizations work within MasterMSM. An important note is that not all discretizations will be sensible for all systems, but as usual the alanine... | Python Code:
%load_ext autoreload
%matplotlib inline
import math
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks", color_codes=True, font_scale=1.5)
sns.set_style({"xtick.direction": "in", "ytick.direction": "in"})
Explanation: Discretizations
Here we show how different dis... |
1,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to tensor flow
Basic models over MNIST dataset
Linear model
NN one layer node
Convolutional model
Tensoboard example
Save & load models
Step1: Get the MNIST data
Step2: Fist model
St... | Python Code:
# Header
# Basic libraries & options
from __future__ import print_function
#Basic libraries
import numpy as np
import tensorflow as tf
print('Tensorflow version: ', tf.__version__)
#Show images
import matplotlib.pyplot as plt
%matplotlib inline
# plt configuration
plt.rcParams['figure.figsize'] = (10, 10) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.