Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
9,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate new columns with average block info
Take average values over two time horizons
6 blocks (~1 min) -> represents the current state (short frequency view)
60 blocks (~10 min) -> repres... | Python Code:
df['txcnt_second'] = df['tx_count'].values / df['blockTime'].values
df['avg_gasUsed_t_perblock'] = df.groupby('block_id')['gasUsed_t'].transform('mean')
df['avg_price_perblock'] = df.groupby('block_id')['price_gwei'].transform('mean')
def rolling_avg(window_size):
price = df[['block_id', 'avg_pric... |
9,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this discussion notebook we will cover the material from lecture 12 abour ensambles and boosting. For consistancy (with the lecture's note), we will use decision trees. However, any other... | Python Code:
# Import all required libraries
from __future__ import division # For python 2.*
import numpy as np
import matplotlib.pyplot as plt
import mltools as ml
np.random.seed(0)
%matplotlib inline
Explanation: In this discussion notebook we will cover the material from lecture 12 abour ensambles and boosting. For... |
9,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generalized Linear Models
Step1: GLM
Step2: Load the data and add a constant to the exogenous (independent) variables
Step3: The dependent variable is N by 2 (Success
Step4: The independ... | Python Code:
%matplotlib inline
import numpy as np
import statsmodels.api as sm
from scipy import stats
from matplotlib import pyplot as plt
plt.rc("figure", figsize=(16,8))
plt.rc("font", size=14)
Explanation: Generalized Linear Models
End of explanation
print(sm.datasets.star98.NOTE)
Explanation: GLM: Binomial respon... |
9,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'awi', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: AWI
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, T... |
9,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Competition assay analysis and thoughts
Here we will analyze two competition assay conducted as a rough beginning to understand how to best design competition assays to the fluorescent kinas... | Python Code:
#import needed libraries
import re
import os
from lxml import etree
import pandas as pd
import pymc
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Explanation: Competition assay analysis and thoughts
Here we will analyze two competition ... |
9,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
En este ejercicio ingresaremos un año y lo imprimiremos como numero romano.
Step1: La idea es ir achicando el año, con el mayor numero romano posible, sin embargo nos dimos cuenta que tenia... | Python Code:
# suponemos que ponemos un año de verdad, por eso no pongo condiciones
año = int(input("Ingrese su año: "))
añooriginal = año
Explanation: En este ejercicio ingresaremos un año y lo imprimiremos como numero romano.
End of explanation
resultado = ""
while año != 0:
if año >= 1000:
veces = año //... |
9,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: FIO-RONM
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transp... |
9,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use reindex for adding missing columns to a dataframe
Step1: Using reindex to add missing columns to a dataframe
https
Step2: This can also be used to get a subset of the columns
Step3: W... | Python Code:
import pandas as pd
df = pd.DataFrame([
{
'a': 1,
'b': 2,
'd': 4
}
])
df
Explanation: Use reindex for adding missing columns to a dataframe
End of explanation
columns = ['a', 'b', 'c', 'd']
df.reindex(columns=columns, fill_value=0)
Explanation: Using reindex to add missing c... |
9,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 11
Step1: To add an item to the dictionary, use square brackets like a list
Step2: Note that order isn't preserved in a dictionary (unlike a list)
The values can be retrieved using... | Python Code:
birthdays = dict()
print( birthdays )
Explanation: Chapter 11: Dictionaries
Contents
- A dictionary is a mapping
- Dictionary as a set of counters
- Looping and dictionaries
- Reverse lookup
- Dictionaries and lists
- Global variables
- Debugging
- Exercises
This notebook is based on "Think Python, 2Ed" by... |
9,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APPKEY is the Application Key for a (free) http
Step1: First set up the necessary conections to drive a LED (see 102 - LEDs - Drive LEDS with the Raspberry Pi GPIO pins for an illustration;... | Python Code:
APPKEY = "******"
Explanation: APPKEY is the Application Key for a (free) http://www.realtime.co/ "Realtime Messaging Free" subscription.
See "104 - Remote deurbel - Een cloud API gebruiken om berichten te sturen" voor meer gedetailleerde info.
End of explanation
import time
import RPi.GPIO as GPIO
GPIO.se... |
9,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Decision Tree of Observable Operators
Part 5
Step1: ... by slicing slice
Step2: ... that is, only the first item first
Step3: ...that is, only the first items take, take_with_time
Step4... | Python Code:
reset_start_time(O.filter) # alias: where
d = subs(O.range(0, 5).filter(lambda x, i: x % 2 == 0))
Explanation: A Decision Tree of Observable Operators
Part 5: Consolidating Streams
source: http://reactivex.io/documentation/operators.html#tree.
(transcribed to RxPY 1.5.7, Py2.7 / 2016-12, Gunther Klessinger... |
9,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Functions
So far in this course we've explored equations that perform algebraic operations to produce one or more results. A function is a way of encapsulating an operation that takes an inp... | Python Code:
# define a function to return x^2 + 2
def f(x):
return x**2 + 2
# call the function
f(3)
Explanation: Functions
So far in this course we've explored equations that perform algebraic operations to produce one or more results. A function is a way of encapsulating an operation that takes an input and prod... |
9,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
read from an Excel file
documentation
Step1: write to a comma separated value (.csv) file
documentation | Python Code:
file_name_string = 'C:/Users/Charles Kelly/Desktop/Exercise Files/02_07/Final/EmployeesWithGrades.xlsx'
employees_df = pd.read_excel(file_name_string, 'Sheet1', index_col=None, na_values=['NA'])
employees_df
Explanation: read from an Excel file
documentation: http://pandas.pydata.org/pandas-docs/stable/gen... |
9,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<hr style="border-top-width
Step1: <hr style="border-top-width
Step2: Summary
The pandas dateframe (DF) are a very flexible data type for postprocessing CALS data. They comes with a rich a... | Python Code:
import sys
sys.path.append('/eos/user/s/sterbini/MD_ANALYSIS/public/')
from myToolbox import *
Explanation: <hr style="border-top-width: 4px; border-top-color: #34609b;">
Using pytimber with pandas
Ideally the main parameters of the CERN Accelerator complex (settings and acquisitions) are stored in CALS (C... |
9,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: First let's check if there are new or deleted files (only matching by file names).
Step2: Cool, no new nor deleted files.
Now let's set up a dataset that, for each table, lin... | Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas as pd
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '345'
NEW_VERSION = '346'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new_version_files = f... |
9,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: JAX에서 TensorFlow 확률(TFP on JAX)
<table class="tfo-notebook-buttons"... | 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... |
9,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indexing and selecting data
Step1: More on NumPy indexing
Step2: Fancy indexing
Apart from indexing with integers and slices NumPy also supports indexing with arrays of integers (so-called... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Explanation: Indexing and selecting data
End of explanation
a = np.array([-2, 3, 4, -5, 5])
print(a)
Explanation: More on NumPy indexing
End of explanation
a[[1, 3]]
Explanation: Fancy indexing
Apart from indexing wit... |
9,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to use
maximum_superleave_length indicates the maximum length of superleaves to consider. Right now, maximum runnable on my local machine is 5.
ev_calculator_max_length indicates the max... | Python Code:
from itertools import combinations
import numpy as np
import pandas as pd
import seaborn as sns
from string import ascii_uppercase
import time as time
%matplotlib inline
maximum_superleave_length = 5
ev_calculator_max_length = 5
log_file = 'log_games.csv'
Explanation: How to use
maximum_superleave_length i... |
9,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 16 – Reinforcement Learning
This notebook contains all the sample code and solutions to the exersices in chapter 16.
Setup
First, let's make sure this notebook works well in both pyt... | Python Code:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
import sys
# to make this notebook's output stable across runs
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.r... |
9,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualisation using
Table of Contents
Notebook Setup
Simple Line Plots
Using different styles for plots
Setting x and y limits
Labeling plots
Label formatting
LaTeX labels
Legends
Grids
Axis... | Python Code:
# only for the notebook
%matplotlib inline
# only in the ipython shell
# %matplotlib
Explanation: Visualisation using
Table of Contents
Notebook Setup
Simple Line Plots
Using different styles for plots
Setting x and y limits
Labeling plots
Label formatting
LaTeX labels
Legends
Grids
Axis scales
Ticks
Multi... |
9,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicio de análisis, exploración y visualización de bases de datos.
Para el siguiente ejercicio vamos a utilizar la base de datos de las Estaciones del Estado de Aguascalientes con un tiem... | Python Code:
# importar librerías
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use("ggplot")
# leer csv
df = pd.read_csv("/Users/jorgemauricio/Documents/Research/INIFAP_Course/data/ags_ejercicio_curso.csv")
# estructura de la base de datos
Exp... |
9,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This script finds the optimal band gaps of mechanical stack III-V-Si solar cells. I uses a detailed balance approach to calculate the I-V of individual subcells. For calculating... | Python Code:
%matplotlib inline
import numpy as np
from scipy.interpolate import interp2d
import matplotlib.pyplot as plt
from scipy.io import savemat
from iii_v_si import calc_2j_si_eta, calc_2j_si_eta_direct
from detail_balanced_MJ import calc_1j_eta
def vary_top_eg(top_cell_qe,n_s=1):
topcell_eg = np.linspace(0.... |
9,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading and interpreting plane wave files
These files are the output of Quantum Espresso using pw2qmcpack, which is contained in some patches to QE shipped with QMCPACK (in the external_file... | Python Code:
#f = h5py.File("../LiH-gamma.pwscf.h5","r")
#f = h5py.File("../LiH-arb.pwscf.h5","r")
f = h5py.File("../../bccH/pwscf.pwscf.h5","r")
Explanation: Reading and interpreting plane wave files
These files are the output of Quantum Espresso using pw2qmcpack, which is contained in some patches to QE shipped with ... |
9,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First Steps
Now that you have installed Marvin, it's time to take your first steps. If you want to learn more about how Marvin works, then go see General Info to learn about Marvin Modes, V... | Python Code:
from __future__ import print_function, division, absolute_import
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: First Steps
Now that you have installed Marvin, it's time to take your first steps. If you want to learn more about how Marvin works, then go see General Info to learn about Mar... |
9,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
12.850 - Assignment 3 | Bryce Corlett
Exploring Convergence Properties
This assignment was motivated by examining the different convergence properties of Jacobi, Gauss-Seidel, and SOR iter... | Python Code:
#Import toolboxes
from scipy import sparse #Allows me to create sparse matrices (i.e. not store all of the zeros in the 'A' matrix)
from scipy.sparse import linalg as linal
from numpy import * #To make matrices and do matrix manipulation
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: 12.8... |
9,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using machine learning techniques
The ideas of
<a href="https
Step1: Parameters
Step2: Load data
Let's load the data
Step3: Let's store features, labels and other d... | Python Code:
# Import
from __future__ import division
get_ipython().magic(u'matplotlib inline')
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['figure.figsize'] = (20.0, 10.0)
inline_rc = dict(mpl.rcParams)
from classification_utilities import make_facies_log_plot
import pandas as pd
import numpy... |
9,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MÓDULO NumPy
Los módulos NumPy (Numerical Python) y SciPy proporcionan funciones y rutinas matemáticas para la manipulación de arrays y matrices de datos numéricos de una forma eficiente.
El... | Python Code:
import numpy as np
Explanation: MÓDULO NumPy
Los módulos NumPy (Numerical Python) y SciPy proporcionan funciones y rutinas matemáticas para la manipulación de arrays y matrices de datos numéricos de una forma eficiente.
El módulo SciPy extiende la funcionalidad de NumPy con una colección de algoritmos mate... |
9,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 6</font>
Download
Step1: Retornando Dados no MongoDB com PyMongo | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 6</font>
Download: http://github.com/dsacademybr
End of explanation
# Imp... |
9,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examles of error propigation
Examples are taken from http
Step1: This version uses prior distributions to do all the work. H and h are both informative priors that then drive the solution t... | Python Code:
import numpy as np
import pymc3 as pm
import seaborn as sns
import arviz as ar
sns.set(font_scale=1.5)
%matplotlib inline
Explanation: Examles of error propigation
Examples are taken from http://ipl.physics.harvard.edu/wp-uploads/2013/03/PS3_Error_Propagation_sp13.pdf and used on MCMC to show how the answe... |
9,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy and Matplotlib Tutorial
Step1: NumPy Arrays
Creation
Step2: Create arrays with array, ones, zeros, empty.
Create 1D-arrays with arange, linspace, logspace.
Create arrays/matrices wit... | Python Code:
from __future__ import print_function
from numpy import *
from matplotlib.pylab import *
%pylab --no-import-all inline
Explanation: NumPy and Matplotlib Tutorial
End of explanation
a1 = array([1.0, 2.0, 3.0])
a2 = arange(1.0, 5.0, 0.5)
a3 = linspace(1.0, 10.0, 17)
print(a1)
print(a2)
print(a3)
m1 = array([... |
9,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 1. Sketch of a cell (top left) with the horizontal (red) and vertical (green) velocity nodes and the cell-centered node (blue). Definition of the normal vector to "surface" (segment) ... | Python Code:
%matplotlib inline
# plots graphs within the notebook
%config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format
import matplotlib.pyplot as plt #calls the plotting library hereafter referred as to plt
import numpy as np
Explanation: Figure 1. Sketch of a cell... |
9,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create an example dataframe
Step2: List unique values | Python Code:
# Import modules
import pandas as pd
# Set ipython's max row display
pd.set_option('display.max_row', 1000)
# Set iPython's max column width to 50
pd.set_option('display.max_columns', 50)
Explanation: Title: List Unique Values In A Pandas Column
Slug: pandas_list_unique_values_in_column
Summary: List Uniqu... |
9,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load fake data into a pandas DataFrame. Use the dt column an the index for the DataFrame
Step1: Convert the type column to a category (similar to factor in R)
Step2: Plot the noise readin... | Python Code:
raw_data = {'dt': ['2017-01-15 00:06:08',
'2017-01-15 01:09:08',
'2017-01-16 02:07:08',
'2017-01-16 02:07:09',
'2017-01-16 03:04:08',
'2017-01-16 03:04:09',
'2017-01-15 01:06:08'],
... |
9,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom observation models
While bayesloop provides a number of observation models like Poisson or AR1, many applications call for different distributions, possibly with some parameters set t... | Python Code:
import bayesloop as bl
import numpy as np
import sympy.stats
from sympy import Symbol
rate = Symbol('lambda', positive=True)
poisson = sympy.stats.Poisson('poisson', rate)
L = bl.om.SymPy(poisson, 'lambda', bl.oint(0, 6, 1000))
Explanation: Custom observation models
While bayesloop provides a number of obs... |
9,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
튜플 활용
주요 내용
파이썬에 내장되어 있는 컬렉션 자료형 중에서 튜플에 대해 알아 본다.
튜플(tuples)
Step1: 튜플의 기본 활용
오늘의 주요 예제의 문제를 해결하려면, 문자열과 사전 자료형 이외의 튜플에 대해
알아 보아야 한다.
튜플은 순서쌍이라고도 불리며, 리스트와 99% 비슷한 용도를 가진다.
리스트와 다른 점은 튜플이... | Python Code:
from __future__ import print_function
Explanation: 튜플 활용
주요 내용
파이썬에 내장되어 있는 컬렉션 자료형 중에서 튜플에 대해 알아 본다.
튜플(tuples): 리스트와 비슷. 하지만 수정 불가능(immutable).
* 사용 형태: 소괄호 사용
even_numbers_tuple = (2, 4, 6, 8, 10)
todays_datatypes_tuple = ('list', 'tuple', 'dictionary')
특징: 임의의 자료형 값들을 섞어서 항목으로 사용 가능
mixed_tuple = (1, '... |
9,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inbuilt Data Structures
Data Structures in a language determine the level of flexibility of using the language. If a Language has efficient, inbuilt data structures then the effort of the pr... | Python Code:
import this
Explanation: Inbuilt Data Structures
Data Structures in a language determine the level of flexibility of using the language. If a Language has efficient, inbuilt data structures then the effort of the programmer is reduced. He does not have to code everything from the scratch. Furthermore, if i... |
9,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Code Repositories
The notebook contains problems oriented around building a basic Python code repository and making it public via Github. Of course there are other places to put code reposi... | Python Code:
! #complete
! #complete
Explanation: Code Repositories
The notebook contains problems oriented around building a basic Python code repository and making it public via Github. Of course there are other places to put code repositories, with complexity ranging from services comparable to github to simple hos... |
9,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ROMS Ocean Model Example
The Regional Ocean Modeling System (ROMS) is an open source hydrodynamic model that is used for simulating currents and water properties in coastal and estuarine reg... | Python Code:
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
%matplotlib inline
import xarray as xr
Explanation: ROMS Ocean Model Example
The Regional Ocean Modeling System (ROMS) is an open source hydrodynamic model that is used for simulating currents a... |
9,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2
This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian perspective. It also contains tips and data visualizatio... | Python Code:
import pymc as pm
parameter = pm.Exponential("poisson_param", 1)
data_generator = pm.Poisson("data_generator", parameter)
data_plus_one = data_generator + 1
Explanation: Chapter 2
This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian per... |
9,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 5
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: If we want to do any "feature engi... | Python Code:
import graphlab
Explanation: Regression Week 5: LASSO (coordinate descent)
In this notebook, you will implement your very own LASSO solver via coordinate descent. You will:
* Write a function to normalize features
* Implement coordinate descent for LASSO
* Explore effects of L1 penalty
Fire up graphlab cre... |
9,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning - Part I
Theory
Two important figures from Chapter 5
Step1: Randomly select 20% of the samples as test set.
Step2: Using cross-validation, try out $d=1,2,\ldots,20$.
Use accu... | Python Code:
import numpy as np
import pandas as pd
from sklearn import svm, datasets
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, train_test_split
# load iris data
iris = datasets.load_iris()
X = iris.data
y = iris.target
X[:3]
y[:3]
Explanation: Deep Learning - Part I
T... |
9,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Before doing anything, define a simple object which will allow us to perform calculations using the properties of air. The object air is defined in the package atmosphere. The object air i... | Python Code:
air = atmos.Air()
Explanation: Before doing anything, define a simple object which will allow us to perform calculations using the properties of air. The object air is defined in the package atmosphere. The object air is a child of the abstract class gas which has two properties, temperature and pressure... |
9,543 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I need to square a 2D numpy array (elementwise) and I have tried the following code: | Problem:
import numpy as np
a = np.arange(4).reshape(2, 2)
power = 5
a = a ** power |
9,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
molPX Di-Ala example
<pre>
Guillermo Pérez-Hernández guille.perez@fu-berlin.de
</pre>
In this notebook we will be using a trajectory of Di-Ala-peptide to easily identify conformations in ... | Python Code:
from os.path import exists
import molpx
from matplotlib import pylab as plt
%matplotlib ipympl
import pyemma
import numpy as np
Explanation: molPX Di-Ala example
<pre>
Guillermo Pérez-Hernández guille.perez@fu-berlin.de
</pre>
In this notebook we will be using a trajectory of Di-Ala-peptide to easily id... |
9,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy 소개
NumPy(보통 "넘파이"라고 발음한다)는 2005년에 Travis Oliphant가 발표한 수치해석용 Python 패키지이다. 다차원의 행렬 자료구조인 ndarray 를 지원하여 벡터와 행렬을 사용하는 선형대수 계산에 주로 사용된다. 내부적으로는 BLAS 라이브러리와 LAPACK 라이브러리에 기반하고 있어서 C로 구현된 ... | Python Code:
import numpy as np
a = np.array([0,1,2,3,4,5,6,7,8,9])
print(type(a))
a
Explanation: NumPy 소개
NumPy(보통 "넘파이"라고 발음한다)는 2005년에 Travis Oliphant가 발표한 수치해석용 Python 패키지이다. 다차원의 행렬 자료구조인 ndarray 를 지원하여 벡터와 행렬을 사용하는 선형대수 계산에 주로 사용된다. 내부적으로는 BLAS 라이브러리와 LAPACK 라이브러리에 기반하고 있어서 C로 구현된 CPython에서만 사용할 수 있으며 Jython, Iro... |
9,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST digit recognition using SVC with poly kernel in scikit-learn
polynomial
Step1: Where's the data?
Step2: How much of the data will we use?
Step3: Read the training images and labels
... | Python Code:
from __future__ import division
import os, time, math, csv
import cPickle as pickle
import matplotlib.pyplot as plt
import numpy as np
from print_imgs import print_imgs # my own function to print a grid of square images
from sklearn.preprocessing import StandardScaler
from sklearn.utils impor... |
9,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supervised Learning
Step1: Imports for plotting
Step2: Now import dataset from scikit learn as well as the linear_model module. Note
Step3: Next we'll download the data set
Step4: Let's ... | Python Code:
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
Explanation: Supervised Learning: Linear Regression
In this section we will be going over LINEAR REGRESSION. We'll be going over how to use the scikit-learn regression model, as well as how to train the regressor using the fit() met... |
9,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MatrixTable Tutorial
If you've gotten this far, you're probably thinking
Step1: There are a few things to note
Step2: MatrixTable operations
We belabored the operations on tables because t... | Python Code:
import hail as hl
from bokeh.io import output_notebook, show
output_notebook()
hl.utils.get_1kg('data/')
mt = hl.read_matrix_table('data/1kg.mt')
mt.describe()
Explanation: MatrixTable Tutorial
If you've gotten this far, you're probably thinking:
"Can't I do all of this in pandas or R?"
"What does this ha... |
9,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Converting a Grammar into <span style="font-variant
Step1: The file c-grammar.g contains a context-free grammar for the language C.
Step2: Our goal is to convert this grammar into an <span... | Python Code:
!cat Grammar.g4
!type Grammar.g4
Explanation: Converting a Grammar into <span style="font-variant:small-caps;">Html</span>
You should store the grammar in the file Grammar.g4. This grammar should describe the lexical structure of the grammar for the language
C that is contained in the file
<a href="http... |
9,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating a Cutout with the SARAH-2 dataset
This walkthrough describes the process of creating a cutout using the SARAH-2 dataset by EUMETSAT.
The SARAH-2 dataset contains extensive informati... | Python Code:
import atlite
import logging
logging.basicConfig(level=logging.INFO)
cutout = atlite.Cutout(path="western-europe-2011-01.nc",
module=["sarah", "era5"],
sarah_dir="/home/vres-climate/data/sarah_v2",
x=slice(-13.6913, 1.7712),
... |
9,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Exponential model
Last time we proposed two candidate models
Step2: Look at both fits together
Which is better? | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
# assign data to arrays
T = np.array([1, 3, 6, 9, 12, 18])
Y = np.array([0.94, 0.77, 0.40, 0.26, 0.24, 0.16])
X = 100*Y
# plot raw data
plt.plot(T, Y, 'o')
plt.xlabel('Retention interval (sec.)')
plt.ylabel('Proportion r... |
9,552 | Given the following text description, write Python code to implement the functionality described.
Description:
Return 2^n modulo p (be aware of numerics).
This is how the function will work:
modp(3, 5)
3
This is how the function will work:
modp(1101, 101)
2
This is how the function will work:
... | Python Code:
def modp(n: int, p: int):
ret = 1
for i in range(n):
ret = (2 * ret) % p
return ret |
9,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
First encountering a new dataset can sometimes feel overwhelming. You might be presented with hundreds or thousands of features without even a description to go by. Where do you... | Python Code:
#$HIDE_INPUT$
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
plt.style.use("seaborn-whitegrid")
df = pd.read_csv("../input/fe-course-data/autos.csv")
df.head()
Explanation: Introduction
First encountering a new dataset can sometimes feel overwhelming. You might... |
9,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note
Step1: Suppose we want to get from A to B. Where can we go from the start state, A?
Step2: We see that from A we can get to any of the three cities ['Z', 'T', 'S']. Which should we ch... | Python Code:
romania = {
'A': ['Z', 'T', 'S'],
'B': ['F', 'P', 'G', 'U'],
'C': ['D', 'R', 'P'],
'D': ['M', 'C'],
'E': ['H'],
'F': ['S', 'B'],
'G': ['B'],
'H': ['U', 'E'],
'I': ['N', 'V'],
'L': ['T', 'M'],
'M': ['L', 'D'],
'N': ['I'],
'O': ['Z', 'S'],
'P': ['R', 'C', 'B'],
'R': ['S', 'C', 'P'],
'S': ['A'... |
9,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, let's make a random binding network. We use the same structure as the circular convolution network
Step1: This seems to give us something like binding. But, can we now unbind?
To d... | Python Code:
D = 16
D_bind = 32
scaling_fudge_factor = 2.0
model = spa.Network()
model.config[nengo.Ensemble].neuron_type=nengo.LIFRate()
with model:
in1 = spa.State(D)
in2 = spa.State(D)
out = spa.State(D)
bind = nengo.networks.Product(n_neurons=50, dimensions=D_bind)
T1 = np.random.normal(siz... |
9,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Neural Network Potentials
An area of significant recent interest is the use of neural networks to model quantum mechanics. Since directly (or approximately) solving Sc... | Python Code:
#@title Imports & Utils
!pip install -q git+https://www.github.com/deepmind/haiku
!pip install -q git+https://www.github.com/deepmind/optax
!pip install -q --upgrade git+https://www.github.com/google/jax-md
# Imports
import os
import numpy as onp
import pickle
import jax
from jax import lax
from jax import... |
9,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Position Management | Contents | Streaming Prices >
Transaction History
Obtain Transaction History
get_transaction_history(self, account_id, **params)
Step1: Get Specifi... | 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",
... |
9,558 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
plot scatter plot between for k
| Python Code::
import matplotlib.pyplot as plt
plt.scatter(k[:,0], k[:,1])
|
9,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started
To begin with, cobrapy comes with bundled models for Salmonella and E. coli, as well as a "textbook" model of E. coli core metabolism. To load a test model, type
Step1: The ... | Python Code:
from __future__ import print_function
import cobra.test
# "ecoli" and "salmonella" are also valid arguments
model = cobra.test.create_test_model("textbook")
Explanation: Getting Started
To begin with, cobrapy comes with bundled models for Salmonella and E. coli, as well as a "textbook" model of E. coli cor... |
9,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lista de Exercícios - SEU NOME
Os exercícios valem 30% da nota final.
Data Entrega
Step1: Teste para as seguintes situações
Step2: Exercício 2
(0.5 ponto) Crie uma função chamda qtde_carac... | Python Code:
def soma_tres_num(x,y,z=10):
return x+y+z
Explanation: Lista de Exercícios - SEU NOME
Os exercícios valem 30% da nota final.
Data Entrega: 18/09/2016
Formato da Entrega: .ipynb - Clique em File -> Download as -> IPython Notebook (.ipynb)
Enviar por email até a data de entrega, onde o assunto do email d... |
9,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment 2
Implement the search algorithm you came up with in pseudocode with Python
Test the search algorithm with a list of 10,100,1000 random numbers (sorted with your sorting algorithm... | Python Code:
import random
Explanation: Assignment 2
Implement the search algorithm you came up with in pseudocode with Python
Test the search algorithm with a list of 10,100,1000 random numbers (sorted with your sorting algorithm) and compare the result using the %time to time your code and submit your results in code... |
9,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Properties
Step4: Comparision bewteen sparse and mixed graph
Step5: Varying sigma in the sparse part of the mixed graph
Step6: Varying tau in the sparse part of the mixed graph
Ste... | Python Code:
mdest = '../result/random_network/mixture/'
sdest = '../result/random_network/sparse/'
m_f = '%d_%.2f_%.2f_%.2f_%.2f_%.2f_%.2f.pkl'
s_f = '%d_%.2f_%.2f_%.2f.pkl'
colors = cm.rainbow(np.linspace(0, 1, 7))
np.random.shuffle(colors)
colors = itertools.cycle(colors)
def degree_dist_list(graph, ddist):
_ddi... |
9,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Density estimation using Real NVP
Authors
Step1: Load the data
Step2: Affine coupling layer
Step4: Real NVP
Step5: Model training
Step6: Performance evaluation | Python Code:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import regularizers
from sklearn.datasets import make_moons
import numpy as np
import matplotlib.pyplot as plt
import tensorflow_probability as tfp
Explanation: Density estimation using Real NVP
A... |
9,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Tabular datasets
The UCI ML repository contains many smallish datasets, mostly tabular.
Kaggle also hosts many interesting datasets.
Sklearn has many small datasets bu... | Python Code:
# Standard Python libraries
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
from IPython import display
import sklearn
import seaborn as sns
sns.set(style="ticks... |
9,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
자료 안내
Step1: 주요 내용
모집단과 표본
모집단 분산의 점추정
주요 예제
21장에서 다룬 미국의 51개 주에서 거래되는 담배(식물)의 도매가격 데이터를 보다 상세히 분석한다.
특히, 캘리포니아 주를 예제로 하여 주(State)별로 담배(식물) 도매가 전체에 대한 거래가의 평균과 분산을 점추정(point estimation)하는 ... | Python Code:
from GongSu21_Statistics_Averages import *
Explanation: 자료 안내: 여기서 다루는 내용은 아래 사이트의 내용을 참고하여 생성되었음.
https://github.com/rouseguy/intro2stats
모집단 분산 점추정
안내사항
지난 시간에 다룬 21장 내용을 활용하고자 한다.
따라서 아래와 같이 21장 내용을 모듈로 담고 있는 파이썬 파일을 임포트 해야 한다.
주의: GongSu21_Statistics_Averages.py 파일이 동일한 디렉토리에 있어야 한다.
End of explanation... |
9,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Session 8 - Source model calibration using PEST and Veneer
PEST is a highly capable system for model calibration, and for sensitivity and uncertainty analysis. PEST is independent of any par... | Python Code:
from veneer.manage import start, create_command_line, kill_all_now
import veneer
veneer_install = 'D:\\src\\projects\\Veneer\\Compiled\\Source 4.1.1.4484 (public version)'
source_version = '4.1.1'
cmd_directory = 'E:\\temp\\veneer_cmd'
path = create_command_line(veneer_install,source_version,dest=cmd_direc... |
9,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Back to data again
On a commencé à analyser les données de Pokemons et à afficher plusieurs graphiques pour avoir une vision de nos données. Le problème avec les données c'est que dans la vr... | Python Code:
Image(url="http://i.giphy.com/LY1DH1AMbG0tq.gif")
Explanation: Back to data again
On a commencé à analyser les données de Pokemons et à afficher plusieurs graphiques pour avoir une vision de nos données. Le problème avec les données c'est que dans la vrai vie, les données ne sont pas propre (dirty data)...... |
9,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to create and use a Secret
A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. In this notebook, we would learn how to create a Se... | Python Code:
from kubernetes import client, config
Explanation: How to create and use a Secret
A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. In this notebook, we would learn how to create a Secret and how to use Secrets as files from a Pod as seen in https:... |
9,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Social Network Analysis
Step1: If we're trying to build a network we need two things
Step2: That's a lot of information! Let's grab out all of the speakers. All the speaker elements will h... | Python Code:
with open("shakespeare_data/plays_xml/othello_ps_v3.xml") as f:
othello_xml = etree.fromstring(f.read().encode())
Explanation: Social Network Analysis: NetworkX
Mark Algee-Hewitt looks at thousands of plays across centuries. But as we've learned so far, to do this we first have to figure out how to cal... |
9,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 2 - Printing and manipulating text
We started the first week by printing Hello world (you can try it below). This taught us a number of things. It taught us about strings, functions, ... | Python Code:
print("Hello world")
Explanation: Week 2 - Printing and manipulating text
We started the first week by printing Hello world (you can try it below). This taught us a number of things. It taught us about strings, functions, statements. As we know, as biologists one of the primary entities that we deal with... |
9,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Criação de imagens sintéticas
Imagens sintéticas são bastante utilizadas nos testes de algoritmos e na geração de
padrões de imagens.
Iremos aprender a gerar os valores dos pixels de uma ima... | Python Code:
import numpy as np
Explanation: Criação de imagens sintéticas
Imagens sintéticas são bastante utilizadas nos testes de algoritmos e na geração de
padrões de imagens.
Iremos aprender a gerar os valores dos pixels de uma imagem a partir de uma equação matemática
de forma muito eficiente, sem a necessidade de... |
9,572 | 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 | 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())... |
9,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análisis de los datos obtenidos
Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 11 ... | Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos el fichero csv co... |
9,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Some utility functions
Step1: Load in the mnist dataset
Step2: Simple logistic regression a' la sklearn
Let's set a baseline with a simple logistic regression, ommiting reguralization. Jus... | Python Code:
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
# Reformat the dataset for the convolutional networks
def reformat(dataset):
dataset = dataset.reshape((-1, image_size, image_size, num_channels)).astype(np... |
9,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dependencies
Step1: Loading Data
First, we want to create our word vectors. For simplicity, we're going to be using a pretrained model.
As one of the biggest players in the ML game, Google... | Python Code:
# Tensorflow
import tensorflow as tf
print('Tested with TensorFlow 1.2.0')
print('Your TensorFlow version:', tf.__version__)
# Feeding function for enqueue data
from tensorflow.python.estimator.inputs.queues import feeding_functions as ff
# Rnn common functions
from tensorflow.contrib.learn.python.learn.e... |
9,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solvers
Step1: General "Fitting" Workflow
PHOEBE includes wrappers around several different inverse-problem "algorithms" with a common interface. These available "algorithms" are divided i... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
import numpy as np
logger = phoebe.logger()
Explanation: Solvers: The Inverse Problem
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 s... |
9,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reminder (Before we start)
Check whether the kernel at the top right is set to "urbs" in order to be able to run this script.
Example 1
Step1: <span style="color
Step2: Now let's solve the... | Python Code:
# Load the object "environ" from the library "pyomo" which is already installed in our urbs environment.
# Whenever we will use it, we will call it using its alias "pyo"
import pyomo.environ as pyo
# Let's create a ConcreteModel object and fill it with life!
model = pyo.ConcreteModel()
model.name = "Exampl... |
9,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 2
Imports
Step2: Factorial
Write a function that computes the factorial of small numbers using np.arange and np.cumprod.
Step4: Write a function that computes the factorial ... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Numpy Exercise 2
Imports
End of explanation
def np_fact(n):
Compute n! = n*(n-1)*...*1 using Numpy.
#Creates array from 1 to n
c = np.arange(1,n+1,1)
#Returns a 1D array of the factorial... |
9,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing binary decision trees
The goal of this notebook is to implement your own binary decision tree classifier. You will
Step1: Load the lending club dataset
We will be using the sam... | Python Code:
import pandas as pd
import numpy as np
Explanation: Implementing binary decision trees
The goal of this notebook is to implement your own binary decision tree classifier. You will:
Use SFrames to do some feature engineering.
Transform categorical variables into binary variables.
Write a function to compute... |
9,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Radial Velocity Offsets (rv_offset)
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... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Radial Velocity Offsets (rv_offset)
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
imp... |
9,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression - Case Study - part 1
A well known case for regression with continuous features is the Boston housing dataset. It is so well known that it is distributed as part of the dat... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn import linear_model
from sklearn.metrics import explained_variance_score, mean_squared_error
from sklearn.model_selection import learning_curve
from sklearn.model_selection import Sh... |
9,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaia TGAS + 2MASS + WISE
The provided Gaia dataset is a dump of the Gaia science archive's match between the astrometry in the Tycho-Gaia Astrometric Solution (TGAS) and photometric sources ... | Python Code:
from os import path
import numpy as np
import astropy.coordinates as coord
import astropy.units as u
from astropy.io import fits
from astropy.table import Table
import matplotlib.pyplot as plt
plt.style.use('notebook.mplstyle')
%matplotlib inline
import numpy as np
data_path = '../data/'
Explanation: Gaia ... |
9,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing binary decision trees
The goal of this notebook is to implement your own binary decision tree classifier. You will
Step1: Load the lending club dataset
We will be using the sam... | Python Code:
import graphlab
Explanation: Implementing binary decision trees
The goal of this notebook is to implement your own binary decision tree classifier. You will:
Use SFrames to do some feature engineering.
Transform categorical variables into binary variables.
Write a function to compute the number of misclass... |
9,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Step1: Set the workspace loglevel to not print anything
Step2: As the paper requires some lengthy calculation we have split it into parts and put the function in a separate noteboo... | Python Code:
import openpnm as op
import scipy as sp
import numpy as np
import matplotlib.pyplot as plt
import openpnm.models.geometry as gm
import openpnm.topotools as tt
%matplotlib inline
np.random.seed(10)
Explanation: Example: Regenerating Data from
R. Wu et al. / Elec Acta 54 25 (2010) 7394–7403
Import the module... |
9,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Publically-available .csv for reproducibility
I generate two files currently named viomet-snapshot-project-df.csv and viomet-2012-snapshot-project-df.csv, which are the September to Novermbe... | Python Code:
metaphors_url = 'http://metacorps.io/static/viomet-snapshot-project-df.csv'
project_df = get_project_data_frame(metaphors_url)
print(project_df.columns)
Explanation: Publically-available .csv for reproducibility
I generate two files currently named viomet-snapshot-project-df.csv and viomet-2012-snapshot-pr... |
9,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bio-IT Hackathon
Step1: FAIRification
We submited the csv file to the fairifier
What did we do?
The CLNACC field, which is RCV#, was used to make a new column for the persistent ID like htt... | Python Code:
import json
import re
import os
import urllib.request as request
import gzip
import argparse
import shutil
from collections import OrderedDict
import os
import re
filePath = 'clinvar.vcf';
outputfile = open('clinvar.csv','w');
################################################
# Helper Methods ... |
9,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo 4. Valores y vectores propios
Si el tensor de esfuerzos en un punto $P$, en el sistema de referencia $X,Y,Z$ está definidido por
Step1: Solución
Step2: Resolviendo vía polinomio ca... | Python Code:
from IPython.display import Image,Latex
#Image()
Image(filename='FIGURES/Sorigen.png',width=400)
Explanation: Ejemplo 4. Valores y vectores propios
Si el tensor de esfuerzos en un punto $P$, en el sistema de referencia $X,Y,Z$ está definidido por:
$$\begin{align}
\
&\sigma_{xx} = 200\dfrac{kgf}{cm^2}; \;\;... |
9,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provide... |
9,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IPython Logbook Manager
This IPython notebook can be used to manage the Logbook via a collection of bash scripts that handle the listing, creating, and backing up of the logbook entries. Eac... | Python Code:
import ConfigParser
CP = ConfigParser.ConfigParser()
CP.read("../.config")
head = CP.get('IPyLogbook-Config','head')
url = CP.get('IPyLogbook-Config','url')
port = CP.get('IPyLogbook-Config','ssh-port')
headLink="[Logbook HEAD]("+url+":"+port+"/tree)"
extensionsLink="[Logbook Extensions]("+url+":"+port+"/n... |
9,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Install + Imports
Step2: Add path to data and projection weights.
NOTE
Step4: Load images... | Python Code:
#@title Default title text
# 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 wri... |
9,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The double dice problem
This notebook demonstrates a way of doing simple Bayesian updates using the table method, with a Pandas DataFrame as the table.
Copyright 2018 Allen Downey
MIT Licens... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
import numpy as np
import pandas as pd
from fractions import Fraction
Explanation: The double ... |
9,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Weights Prediction
Step1: Data import and cleaning
Step2: The data are messed up; name fields contain commas in a comma-separated file so two extra columns are created.
Step3: Clea... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import pymc3 as pm
from pymc3.gp.util import plot_gp_dist
import theano.tensor as tt
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('dark')
Explanation: Linear Weights Prediction
End of explanation
seasonal_pitch_raw = pd.read_c... |
9,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img align="left" src="imgs/logo.jpg" width="50px" style="margin-right
Step1: I. Loading Labeling Matricies
First we'll load our label matrices from notebook 2
Step2: Now we set up and run... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import re
import numpy as np
# Connect to the database backend and initalize a Snorkel session
from lib.init import *
from snorkel.models import candidate_subclass
from snorkel.annotations import load_gold_labels
from snorkel.lf_helpers import... |
9,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Escaping particles
Sometimes we are not interested in particles that get too far from the central body. Here we will define a radius beyond which we remove particles from the simulation. L... | Python Code:
import rebound
import numpy as np
def setupSimulation():
sim = rebound.Simulation()
sim.add(m=1., hash="Sun")
sim.add(x=0.4,vx=5., hash="Mercury")
sim.add(a=0.7, hash="Venus")
sim.add(a=1., hash="Earth")
sim.move_to_com()
return sim
sim = setupSimulation()
sim.status()
Explanati... |
9,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
9,596 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following DataFrame: | Problem:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Col1': [1, 4, 7, 10, 13, 16],
'Col2': [2, 5, 8, 11, 14, 17],
'Col3': [3, 6, 9, 12, 15, 18],
'Type': [1, 1, 2, 2, 3, 3]})
List = np.random.permutation(len(df))
def g(df, List):
return df.iloc[... |
9,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
20150111_2DPlotsonPythonP3
Two-dimensional plots on Python [Part III]
Support material for the blog post "Two-dimensional plots on Python [Part III]", on Programming Science.
Author
Step1: ... | Python Code:
from pylab import *
t = arange(0.0,2.0,0.01)
y1 = sin(2*pi*t)
y2 = cos(2*pi*t)
fig, ax = subplots(2, sharex=True)
ax[0].plot(t, y1, color='green', linestyle='-.', linewidth=3)
ax[1].plot(t, y2, color='red', linestyle=':', linewidth=3)
show()
Explanation: 20150111_2DPlotsonPythonP3
Two-dimensional p... |
9,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Consistency testing
For most problems, multiple flux states can achieve the same optimum and thus we try to obtain a consistent network. By this, we mean that there will be mulitple blocked ... | Python Code:
import cobra
test_model = cobra.Model("test_model")
v1 = cobra.Reaction("v1")
v2 = cobra.Reaction("v2")
v3 = cobra.Reaction("v3")
v4 = cobra.Reaction("v4")
v5 = cobra.Reaction("v5")
v6 = cobra.Reaction("v6")
test_model.add_reactions([v1, v2, v3, v4, v5, v6])
v1.reaction = "-> 2 A"
v2.reaction = "A <-> B"
v... |
9,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with Caffe on Docker environment
21 Octuber 2015
Alejandro Cartas
1. Introduction
What is a Deep Learning programming framework?
Is a combination of specialized hardware and ... | Python Code:
import caffe
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import matplotlib as mpl
import numpy as np
import os
import struct
%matplotlib inline
Explanation: Getting started with Caffe on Docker environment
21 Octuber 2015
Alejandro Cartas
1. Introduction
What is a Deep Learning pro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.