Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
10,900
Given the following text description, write Python code to implement the functionality described below step by step Description: B2b example notebook Example notebook for the B2b, 2 channel 24-bit ADC module. The module contains the same ADCs as the D4 and is identical in hardware to the D4b module Step1: Open the SP...
Python Code: from spirack import SPI_rack, B2b_module, D5a_module, D4b_module import logging from time import sleep from tqdm import tqdm_notebook import numpy as np from scipy import signal from plotly.offline import init_notebook_mode, iplot, plot import plotly.graph_objs as go init_notebook_mode(connected=True) logg...
10,901
Given the following text description, write Python code to implement the functionality described below step by step Description: 1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians. Do a search and print a list of 50 that are playable in the USA (or the country of your choice), along with their popula...
Python Code: import requests response = requests.get('https://api.spotify.com/v1/search?query=artist:lil&type=artist&market=us&limit=50') data = response.json() artists = data['artists']['items'] for artist in artists: print(artist['name'], artist['popularity']) Explanation: 1) With "Lil Wayne" and "Lil Kim" there ...
10,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating $\pi$ by Sampling Points By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie Notebook released under the Creative Commons Attribution 4.0 License. A stochastic way to e...
Python Code: # Import libraries import math import numpy as np import matplotlib.pyplot as plt in_circle = 0 outside_circle = 0 n = 10 ** 4 # Draw many random points X = np.random.rand(n) Y = np.random.rand(n) for i in range(n): if X[i]**2 + Y[i]**2 > 1: outside_circle += 1 else: in_circle ...
10,903
Given the following text description, write Python code to implement the functionality described below step by step Description: Orientation density functions Step1: In this Python Notebook we will show how to properly run a simulation of a composite material, providing the ODF (orientation density function) of the r...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from simmit import smartplus as sim from simmit import identify as iden import os dir = os.path.dirname(os.path.realpath('__file__')) Explanation: Orientation density functions End of explanation x = np.arange(0,182,2...
10,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial about statistical methods The following contains a sequence of simple exercises, designed to get familiar with using Minuit for maximum likelihood fits and emcee to determine parame...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Tutorial about statistical methods The following contains a sequence of simple exercises, designed to get familiar with using Minuit for maximum likelihood fits and emcee to determine parameters by MCMC. Commands are general...
10,905
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="https Step1: DO NOTICE , this is extremely SLOW! Step2: IPython parallel IPython's power is not limited to its advanced shell. Its parallel package includes a framework to setup ...
Python Code: %pylab inline # with plt.xkcd(): fig = plt.figure(figsize=(10, 10)) ax = plt.axes(frameon=False) plt.xlim(-1.5,1.5) plt.ylim(-1.5,1.5) circle = plt.Circle((0.,0.), 1., color='w', fill=False) rect = plt.Rectangle((-1,-1), 2, 2, color='gray') plt.gca().add_artist(rect) plt.gca().add_artist(circle) plt.arrow(...
10,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Figures A “figure” in matplotlib means the whole window in the user interface. Within this figure there can be “sub-plots”. A figure is the windows in the GUI that has “Figure #” as title. Figu...
Python Code: # generating some data points X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # creating a figure fig = plt.figure(figsize=(4,3), dpi=120) #plotting plt.plot(X, C, linestyle='--') plt.plot(X, S) # plotting plt.show() # creating a figure fig = plt.figure(figsize=(4,3), dpi=120...
10,907
Given the following text description, write Python code to implement the functionality described below step by step Description: SARIMAX Step1: ARIMA Example 1 Step2: Thus the maximum likelihood estimates imply that for the process above, we have Step3: To understand how to specify this model in Statsmodels, first ...
Python Code: %matplotlib inline import numpy as np import pandas as pd from scipy.stats import norm import statsmodels.api as sm import matplotlib.pyplot as plt from datetime import datetime import requests from io import BytesIO Explanation: SARIMAX: Introduction This notebook replicates examples from the Stata ARIMA ...
10,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with data in Python Notebook version Step1: 1. Data generation One of the first things we need to learn is to generate random samples from a given distribution. Most things in life ...
Python Code: # Let's import some libraries import numpy as np import matplotlib.pyplot as plt Explanation: Working with data in Python Notebook version: * 1.0 (Sep 3, 2018) - First TMDE version * 1.1 (Sep 14, 2018) - Minor fixes Authors: Vanessa Gómez Verdejo (vanessa@tsc.uc3m.es), Óscar García Hinde (oghinde@tsc.uc3...
10,909
Given the following text description, write Python code to implement the functionality described below step by step Description: The toehold problem The "toehold problem" is named after a tech support response from Gurobi. The nature of the problem is that in order to take advantage of the algebraic constraint modelin...
Python Code: def exception_thrown(f): try: f() except Exception as e: return str(e) Explanation: The toehold problem The "toehold problem" is named after a tech support response from Gurobi. The nature of the problem is that in order to take advantage of the algebraic constraint modeling provide...
10,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Modelling Carrer Choices The model is based on the following research paper Step1: Load Resources Step2: Parametrization Step3: Derived Attributes Step4: Auxiliary Functions Step5: Solv...
Python Code: %matplotlib inline Explanation: Modelling Carrer Choices The model is based on the following research paper: Derek Neal (1999). The Complexity of Job Mobility among Young Men, Journal of Labor Economics, 17(2), 237-261. The implementation draws heavily from the material provided on the Quantitative Economi...
10,911
Given the following text description, write Python code to implement the functionality described below step by step Description: General Structured Output Models with Shogun Machine Learning Toolbox Shell Hu (GitHub ID Step2: Few examples of the handwritten words are shown below. Note that the first capitalized lette...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import numpy as np import scipy.io dataset = scipy.io.loadmat(os.path.join(SHOGUN_DATA_DIR, 'ocr/ocr_taskar.mat')) # patterns for training p_tr = dataset['patterns_train'] # patterns for testing p_ts = ...
10,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Product of 4 consecutive numbers is always 1 less than a perfect square <p> <center>Shubhanshu Mishra (<a href="https Step1: Let us look at the right hand side of the equation first, i.e. $...
Python Code: i_max = 4 nums = np.arange(0, 50)+1 consecutive_nums = np.stack([ np.roll(nums, -i) for i in range(i_max) ], axis=1)[:-i_max+1] n_prods = consecutive_nums.prod(axis=1) df = pd.DataFrame(consecutive_nums, columns=[f"n{i+1}" for i in range(i_max)]) df["prod"] = n_prods df["k"] = np.sqrt(n_prods+1).as...
10,913
Given the following text description, write Python code to implement the functionality described below step by step Description: Taxonomy assignment of simulated communities This notebook demonstrates how to assign taxonomy to communities simulated from natural compositions. These data are stored in the precomputed-re...
Python Code: from os.path import join, expandvars from joblib import Parallel, delayed from glob import glob from os import system from tax_credit.simulated_communities import copy_expected_composition from tax_credit.framework_functions import (parameter_sweep, generate_per...
10,914
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../../../images/qiskit-heading.gif" alt="Note Step1: Quantum Teleportation<a id='teleportation'></a> Quantum teleportation is a protocol to transmit quantum states from one locati...
Python Code: # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, IBMQ, execute # import basic plot tools from qiskit.tools.visualization import matplotlib_circ...
10,915
Given the following text description, write Python code to implement the functionality described below step by step Description: Using ticdat to build modular engines The goal of the ticdat package is to facilitate solve engines that are modular and robust. For example, the multicommodity netflow.py engine can read an...
Python Code: commodities = [['Pencils', 0.5], ['Pens', 0.2125]] # a one column table can just be a simple list nodes = ['Boston', 'Denver', 'Detroit', 'New York', 'Seattle'] cost = [['Pencils', 'Denver', 'Boston', 10.0], ['Pencils', 'Denver', 'New York', 10.0], ['Pencils', 'Denver', 'Seattle', 7.5], ...
10,916
Given the following text description, write Python code to implement the functionality described below step by step Description: Generating a basic map image in Earth Engine Install ee-python Follow the installation directions found here Step1: Visualize Geographic Data Step3: Try it with mapclient This code will ru...
Python Code: # Import the Earth Engine Python Package into Python environment. import ee import ee.mapclient # Initialize the Earth Engine object, using the authentication credentials. ee.Initialize() Explanation: Generating a basic map image in Earth Engine Install ee-python Follow the installation directions found he...
10,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Function h2stats Synopse The h2stats function computes several statistics given an image histogram. g = h2stats(h) Output g Step1: Examples Step2: Numeric Example Step3: Image Example
Python Code: def h2stats(h): import numpy as np import ia898.src as ia hn = 1.0*h/h.sum() # compute the normalized image histogram v = np.zeros(11) # number of statistics # compute statistics n = len(h) # number of gray values v[0] = np.sum((np.arange(n)*hn)) # mean v[1] = np.sum(np.po...
10,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
10,919
Given the following text description, write Python code to implement the functionality described below step by step Description: 定義 Input 及 Output 暫存變數 Input 為 28x28 的點陣圖素 Output 為 10 個 Label Array ,分別代表著 0~9 的預測值 Step1: Cost Functoin 請參考 Step2: 以下進行開始進行實際運算
Python Code: x = tf.placeholder(tf.float32,shape=[None,28*28]) y = tf.placeholder(tf.float32,shape=[None,10]) # Create model # Set model weights W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) xw = tf.matmul(x, W) r = xw + b a = tf.nn.softmax(r) Explanation: 定義 Input 及 Output 暫存變數 Input 為 28x28 的點陣...
10,920
Given the following text description, write Python code to implement the functionality described below step by step Description: Two stage neural network implementation for MNIST digits classifier using Start Overview This is a step by step implementation of a multilayer neural network for MNIST digit classification u...
Python Code: import numpy as np import mnist.utils.load_mnist as load_mnist import start.neural_network as nn import start.layer_dict as ld import start.weight_update_params as wup Explanation: Two stage neural network implementation for MNIST digits classifier using Start Overview This is a step by step implementation...
10,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyse de clusters Step1: On récupère les channels trouvés grace a l'analyse de clusters Step2: One sample ttest FDR corrected (per electrode) Step3: Tests de 280 a 440, par fenetres de...
Python Code: nperm = 1000 T_obs_bin,clusters_bin,clusters_pb_bin,H0_bin = mne.stats.spatio_temporal_cluster_test(X_bin,threshold=None,n_permutations=nperm,out_type='mask') T_obs_ste,clusters_ste,clusters_pb_ste,H0_ste = mne.stats.spatio_temporal_cluster_test(X_ste,threshold=None,n_permutations=nperm,out_type='mask') Ex...
10,922
Given the following text description, write Python code to implement the functionality described below step by step Description: Density of States Analysis Example Given sample and empty-can data, compute phonon DOS To use this notebook, first click jupyter menu File->Make a copy Click the title of the copied jupyter ...
Python Code: workdir = '/SNS/users/lj7/reduction/ARCS/getdos-demo-test' !mkdir -p {workdir} %cd {workdir} Explanation: Density of States Analysis Example Given sample and empty-can data, compute phonon DOS To use this notebook, first click jupyter menu File->Make a copy Click the title of the copied jupyter notebook an...
10,923
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 5</font> Download Step1: Classes Para criar uma classe, utiliza-se a palavra reservada class. O nome da sua classe se...
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 5</font> Download: http://github.com/dsacademybr End of explanation # Cri...
10,924
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1h', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NASA-GISS Source ID: GISS-E2-1H Sub-Topics: Radiative Forcings. ...
10,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 6 Step1: Problem set #2 Step2: Problem set #3 Step3: Problem set #4 Step4: Problem set #5 Step5: Specifying a field other than name, area or elevation for the sort parameter sh...
Python Code: import requests data = requests.get('http://localhost:5000/lakes').json() print(len(data), "lakes") for item in data[:10]: print(item['name'], "- elevation:", item['elevation'], "m / area:", item['area'], "km^2 / type:", item['type']) Explanation: Homework 6: Web Applications For this homework, you're ...
10,926
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', 'ncar', 'sandbox-2', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: NCAR Source ID: SANDBOX-2 Topic: Atmoschem Sub-Topics: Transport, Emi...
10,927
Given the following text description, write Python code to implement the functionality described below step by step Description: Objects Python is an object oriented language. As such it allows the definition of classes. For instance lists are also classes, that's why there are methods associated with them (i.e. appen...
Python Code: class Circle: def __init__(self, radius): self.radius = radius #all attributes must be preceded by "self." Explanation: Objects Python is an object oriented language. As such it allows the definition of classes. For instance lists are also classes, that's why there are methods associated with t...
10,928
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise Step1: Step 1 Step2: Since these are just plain wave files, we can listen to the data using aplay Step3: This has loaded each of the wave files into sound_files[], one for each o...
Python Code: # standard imports import numpy as np import scipy.io.wavfile as wavfile import scipy.signal as sig import matplotlib.pyplot as plt import sklearn.preprocessing, sklearn.cluster, sklearn.tree, sklearn.neighbors, sklearn.ensemble, sklearn.multiclass, sklearn.feature_selection import ipy_table import sklearn...
10,929
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objectives Show PSD of ASK for random data Spectra are determined using FFT and averaging along several realizations <b> Note Step1: Function for determining the impulse respons...
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(18, 10) ) Explanation: Content and Objectives Show PSD ...
10,930
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing Cells in NetPyNE (1) Clone repository and compile mod files Determine your location in the directory structure Step1: Move to (or stay in) the '/content' directory Step2: Ensure ...
Python Code: !pwd Explanation: Importing Cells in NetPyNE (1) Clone repository and compile mod files Determine your location in the directory structure End of explanation %cd /content/ Explanation: Move to (or stay in) the '/content' directory End of explanation !pwd Explanation: Ensure you are in the correct directory...
10,931
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I want to use the pandas apply() instead of iterating through each row of a dataframe, which from my knowledge is the more efficient procedure.
Problem: import numpy as np import pandas as pd a = np.arange(4) df = pd.DataFrame(np.repeat([1, 2, 3, 4], 4).reshape(4, -1)) df = pd.DataFrame(df.values - a[:, None], df.index, df.columns)
10,932
Given the following text description, write Python code to implement the functionality described below step by step Description: The first objective of this notebook is to implement the next function (to extract sample intervals from the total period). Step1: Let's define the parameters as constants, just to do some ...
Python Code: def generate_train_intervals(data_df, train_time, base_time, step, days_ahead, today): pass Explanation: The first objective of this notebook is to implement the next function (to extract sample intervals from the total period). End of explanation # I will try to keep the convention to name with the "d...
10,933
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Verily Life Sciences LLC Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https Step1: Helper methods for visualization ...
Python Code: import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('ticks') import functools import importlib.resources import numpy as np import os import pandas as pd pd.plotting.register_matplotlib_converters() import xarray as xr from IPython.display import display # bsst impo...
10,934
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding text (and handling it in Python) Fiona Pigott A Python notebook to teach you everything you never wanted to know about text encoding (specifically ASCII, UTF-8, and the differ...
Python Code: !printf "hi\n" !printf "hi" | xxd -g1 !printf "hi" | xxd -b -g1 # Generate a list of all of the ASCII characters: # 'unichr' is a built-in Python function to take a number to a unicode code point # (I'll talk more about this and some other built-ins later) for i in range(0,128): print str(i) + " -> " ...
10,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix Factorization via Singular Value Decomposition Matrix factorization is the breaking down of one matrix in a product of multiple matrices. It's extremely well studied in mathematics, a...
Python Code: import pandas as pd import numpy as np movies_df = pd.read_csv('movies.csv') movies_df['movie_id'] = movies_df['movie_id'].apply(pd.to_numeric) movies_df.head(3) ratings_df=pd.read_csv('ratings.csv') ratings_df.head(3) Explanation: Matrix Factorization via Singular Value Decomposition Matrix factorization ...
10,936
Given the following text description, write Python code to implement the functionality described below step by step Description: PYT-DS SAISOFT Overview 2 Overview 3 <a data-flickr-embed="true" href="https Step1: I emphasize this is not really chess. Chess masters do not think in terms of west and east, nor is the ...
Python Code: import numpy as np import pandas as pd squares = np.array(list(64 * " "), dtype = np.str).reshape(8,8) squares print('♔♕♖') squares[0][0] = '♖' squares[7][0] = '♖' squares[0][7] = '♖' squares[7][7] = '♖' squares chessboard = pd.DataFrame(squares, index=range(1,9), columns = ['wR'...
10,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulating Membrane Potential The simulation scripts described in this chapter are available at STEPS_Example repository. This chapter introduces the concept of simulating the electric poten...
Python Code: from __future__ import print_function # for backward compatibility with Py2 import steps.model as smodel import steps.geom as sgeom import steps.rng as srng import steps.solver as ssolver import steps.utilities.meshio as meshio import numpy import math import time from random import * Explanation: Simulati...
10,938
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear algebra overview projection example Linear algebra is the study of vectors and linear transformations. This notebook introduces concepts form linear algebra in a birds-eye overview. T...
Python Code: # setup SymPy from sympy import * x, y, z, t = symbols('x y z t') init_printing() # a vector is a special type of matrix (an n-vector is either a nx1 or a 1xn matrix) Vector = Matrix # define alias Vector so I don't have to explain this during video # setup plotting %matplotlib inline import matplotlib.p...
10,939
Given the following text description, write Python code to implement the functionality described below step by step Description: Numeri In questa pagina introdurremo diversi insiemi di numeri, facendosi aiutare da un sistema di calcolo simbolico Step1: $\mathbb{N}$ L'insieme dei Naturali $\mathbb{N} = \lbrace 0, 1, 2...
Python Code: from sympy import * init_printing() x = symbols('x') x**2 Explanation: Numeri In questa pagina introdurremo diversi insiemi di numeri, facendosi aiutare da un sistema di calcolo simbolico: End of explanation eq = Eq(x + 3, 2, evaluate=False) eq Explanation: $\mathbb{N}$ L'insieme dei Naturali $\mathbb{N} =...
10,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Installating R on WinPython This procedure applys for Winpython (Version of December 2015 and after) 1 - Downloading R binary Step1: 2 - checking and Installing R binary in the right place...
Python Code: import os import sys import io # downloading R may takes a few minutes (80Mo) try: import urllib.request as urllib2 # Python 3 except: import urllib2 # Python 2 # specify R binary and (md5, sha1) hash # R-3.4.3: r_url = "https://cran.r-project.org/bin/windows/base/old/3.5.0/R-3.5.0-win.exe" hashe...
10,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer Learning on TPUs In the <a href="3_tf_hub_transfer_learning.ipynb">previous notebook</a>, we learned how to do transfer learning with TensorFlow Hub. In this notebook, we're going t...
Python Code: import os PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] BUCKET = PROJECT os.environ["BUCKET"] = BUCKET Explanation: Transfer Learning on TPUs In the <a href="3_tf_hub_transfer_learning.ipynb">previous notebook</a>, we learned how to do transfer learning with TensorFlow Hub. In this...
10,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Expressão Regular Pesquisando Step1: Também podemos utilizar a flag IGNORECASE Step2: Extraindo partes de um ER Step3: Encontrando todas as ocorrências Para encontrar todas as ocorrências...
Python Code: import re texto = 'um exemplo palavra:python!!' match = re.search('python', texto) print(match) if match: print('encontrou: ' + match.group()) else: print('não encontrou') Explanation: Expressão Regular Pesquisando End of explanation texto = "GGATCGGAGCGGATGCC" match = re.search(r'a[tg]c', texto, r...
10,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning for Communications By Jakob Hoydis, Contact jakob.hoydis@nokia-bell-labs.com This code is provided as supplementary material to the tutorial Deep Learning for Communications. ...
Python Code: import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf import numpy as np from pprint import pprint %matplotlib inline import matplotlib.pyplot as plt seed = 1337 tf.set_random_seed(seed) np.random.seed(seed) Explanation: Deep Learning for Communications By Jakob Hoydis, Contact jakob.h...
10,944
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Operation-Research-Quick-Intro-Via-Ortools" data-toc-modified-id="Operation-...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic to print version # 2. magic so that t...
10,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison of FastText and Word2Vec Facebook Research open sourced a great project recently - fastText, a fast (no surprise) and effective method to learn word representations and perform te...
Python Code: import nltk nltk.download('brown') # Only the brown corpus is needed in case you don't have it. # Generate brown corpus text file with open('brown_corp.txt', 'w+') as f: for word in nltk.corpus.brown.words(): f.write('{word} '.format(word=word)) # Make sure you set FT_HOME to your fastText dir...
10,946
Given the following text description, write Python code to implement the functionality described below step by step Description: FrameNet I see three ways of getting features from FrameNet Step2: 1. Does word $j$ evoke frame $i$? In sum Step3: Most words evoke one frame, some two, few three. Step7: 2. Frame relatio...
Python Code: import numpy as np import pandas as pd from nltk.corpus import framenet as fn Explanation: FrameNet I see three ways of getting features from FrameNet: Does word $j$ evoke frame $i$? Something with frame relations Something with frame elements End of explanation def get_lus(frame): Helper to get lexeme...
10,947
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST in Keras with Tensorboard This sample trains an "MNIST" handwritten digit recognition model on a GPU or TPU backend using a Keras model. Data are handled using the tf.data.Datset API....
Python Code: BATCH_SIZE = 64 LEARNING_RATE = 0.02 # GCS bucket for training logs and for saving the trained model # You can leave this empty for local saving, unless you are using a TPU. # TPUs do not have access to your local instance and can only write to GCS. BUCKET="" # a valid bucket name must start with gs:// tra...
10,948
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a random braid with a 25 node network, and a probability that any given node will produce a block in a given tick of $$\frac{2^{246}}{2^{256}-1} \simeq 0.1\%.$$ With 25 nodes this mea...
Python Code: try: del n # this is here so that if you re-execute this block, it will create a new network except: pass n = Network(25, target=2**246) # A smaller network or lower target makes thinner braids for dummy in range(500): n.tick(mine=False) b = n.nodes[0].braids[0] b.plot(numberver...
10,949
Given the following text description, write Python code to implement the functionality described below step by step Description: Start with the Final Design Report - SpaceX Hyperloop Competition II for high level view. SpaceX Hyperloop Track Specification Step1: Ball Screws, for the (Eddy current) Brake Mechanism c...
Python Code: import sympy from sympy import Eq, solve, Symbol, symbols, pi from sympy import Rational as Rat from sympy.abc import tau,l,F Explanation: Start with the Final Design Report - SpaceX Hyperloop Competition II for high level view. SpaceX Hyperloop Track Specification End of explanation eta_1 = Symbol('eta_...
10,950
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color=Teal>ATOMIC STRING FUNCTIONS and SPACETIME QUANTIZATION MODELS (Python Code)</font> By Sergei Eremenko, PhD, Dr.Eng., Professor, Honorary Professor https Step1: <font color=teal...
Python Code: import numpy as np import pylab as pl pl.rcParams["figure.figsize"] = 9,6 ################################################################### ##This script calculates the values of Atomic Function up(x) (1971) ################################################################### ################### One Pulse...
10,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Signal-space separation (SSS) and Maxwell filtering This tutorial covers reducing environmental noise and compensating for head movement with SSS and Maxwell filtering. Step1: Backgroun...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False) raw.crop(tmax=60).load_data() Explan...
10,952
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactive time series with time slice retrieval This notebook shows you how to use interactive plots to select time series for different locations and retrieve the imagery that corresponds...
Python Code: %pylab notebook from __future__ import print_function import datacube import xarray as xr from datacube.storage import masking from datacube.storage.masking import mask_to_dict from matplotlib import pyplot as plt from IPython.display import display import ipywidgets as widgets dc = datacube.Datacube(app='...
10,953
Given the following text description, write Python code to implement the functionality described below step by step Description: PyData.Tokyo Tutorial & Hackathon #1 PyData.Tokyoでは毎月開催している中上級者向けの勉強会に加え、初心者の育成を目的としたチュートリアルイベントを開催します。今回のイベントでは下記の項目にフォーカスします。 データの読み込み データの前処理・整形 集計・統計解析 データの可視化 機械学習を使った分類モデルの生成 モデル分類結果の検...
Python Code: from IPython.display import Image Image(url='http://graphics8.nytimes.com/images/section/learning/general/onthisday/big/0415_big.gif') Explanation: PyData.Tokyo Tutorial & Hackathon #1 PyData.Tokyoでは毎月開催している中上級者向けの勉強会に加え、初心者の育成を目的としたチュートリアルイベントを開催します。今回のイベントでは下記の項目にフォーカスします。 データの読み込み データの前処理・整形 集計・統計解析 データ...
10,954
Given the following text description, write Python code to implement the functionality described below step by step Description: Template for test Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation. Included is N Phosphorylation however no benchmarks are av...
Python Code: from pred import Predictor from pred import sequence_vector from pred import chemical_vector Explanation: Template for test End of explanation par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] benchmarks = ["Data/Benchmarks/phos_CDK1.csv", "Data/Benchmarks/phos_CK2.csv", "Data...
10,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Issue 12 The purpose of this notebook is to debug issue 12 Here is the Pyramid version info Step1: Read the data in Step2: Determining the periodicity Our issue filer claims that the perio...
Python Code: import pmdarima as pm print("Pyramid version: %r" % pm.__version__) Explanation: Issue 12 The purpose of this notebook is to debug issue 12 Here is the Pyramid version info: End of explanation import pandas as pd data = pd.read_csv('dummy_data.csv') data.head() Explanation: Read the data in: End of explana...
10,956
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I get how to use pd.MultiIndex.from_tuples() in order to change something like
Problem: import pandas as pd import numpy as np l = [('A', '1', 'a'), ('A', '1', 'b'), ('A', '2', 'a'), ('A', '2', 'b'), ('B', '1','a'), ('B', '1','b')] np.random.seed(1) df = pd.DataFrame(np.random.randn(5, 6), columns=l) def g(df): df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Middle','Lower...
10,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Average wage in Russia Step1: Для выполнения этого задания нам понадобятся данные о среднемесячных уровнях заработной платы в России Step2: Проверка стационарности и STL-декомпозиция ряда ...
Python Code: from __future__ import division import numpy as np import pandas as pd from scipy import stats import statsmodels.api as sm %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import warnings from itertools import product from datetime import * from dateutil.relativedelta import * from...
10,958
Given the following text description, write Python code to implement the functionality described below step by step Description: <table> <tr align=left><td><img align=left src="https Step1: Mixed Equations In-Class Project Consider the reaction-diffusion PDE $$\begin{aligned} u_t &= \sigma D_1 \nabla^2 u + f(u, ...
Python Code: %matplotlib inline import numpy import matplotlib.pyplot as plt import scipy.sparse as sparse import scipy.sparse.linalg as linalg Explanation: <table> <tr align=left><td><img align=left src="https://i.creativecommons.org/l/by/4.0/88x31.png"> <td>Text provided under a Creative Commons Attribution license...
10,959
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Daymet Data Download</h1> Daymet data can be extracted/downloaded in two ways. The nationwide or localized grid can be downloaded; alternately, the data for particular grid cells can be...
Python Code: import urllib import os from datetime import date as dt Explanation: <h1>Daymet Data Download</h1> Daymet data can be extracted/downloaded in two ways. The nationwide or localized grid can be downloaded; alternately, the data for particular grid cells can be extracted through a web interface. <h2>Daymet D...
10,960
Given the following text description, write Python code to implement the functionality described below step by step Description: Better Long-Term Stock Forecasts by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction The previous paper showed a strong predictive relationship between the P/Sales ratio ...
Python Code: %matplotlib inline # Imports from Python packages. import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import pandas as pd import numpy as np import os # Imports from FinanceOps. from curve_fit import CurveFitReciprocal from data_keys import * from data import load_index_data, load_...
10,961
Given the following text description, write Python code to implement the functionality described below step by step Description: No real difference between grain sizes for the parallel vs perpendicular graphite. Step1: Make a giant comparison plot
Python Code: ABIG = 1.0 big_sil = SingleGrainPop('Grain', 'Silicate', 'Mie', amax=ABIG, md=MD) big_gra = SingleGrainPop('Grain', 'Graphite', 'Mie', amax=ABIG, md=MD) %%time big_sil.calculate_ext(EVALS, unit='kev', theta=THVALS) %%time big_gra.calculate_ext(EVALS, unit='kev', theta=THVALS) ax = plt.subplot(111) big_sil...
10,962
Given the following text description, write Python code to implement the functionality described below step by step Description: 나이브베이즈로 들어가겠다. 텍스트 분석은 나이브 베이즈가 Good 텍스트 분석이다 보니 텍스트 처리 기능을 알아야 한다. Python 문자열 인코딩 문자와 인코딩 문자의 구성 바이트 열 Byte Sequence Step1: 유니코드 리터럴(Literal) 따옴표 앞에 u자를 붙이면 unicode 문자열로 인식 내부적으로 유니코드 포...
Python Code: c = "a" c print(c), type(c) #python2 기준. 인코딩 문제로 '가'가 아닌 특수문자들이 뜨는 경우가 있다. python3에서 실행할 경우에는 unicode로 되어 있기 때문에 #전부 정상적으로 한글 문자를 인식할 것이다. x = "가" x print(x) print(x.__repr__()) x = ["가"] print(x), type(x) x = "가" len(x), type(x) x = "ABC" y = "가나다" print(len(x), len(y)) print(x[0], x[1], x[2]) print(y[0],...
10,963
Given the following text description, write Python code to implement the functionality described below step by step Description: Adaptive histogram This type of histogram automatically adapts bins when new values are added. Note that only fixed-width continuous binning scheme is currently supported. Step1: Adding sin...
Python Code: # Necessary import evil import physt from physt import h1, h2, histogramdd import numpy as np import matplotlib.pyplot as plt # Create an empty histogram h = h1(None, "fixed_width", bin_width=10, name="People height", axis_name="cm", adaptive=True) h Explanation: Adaptive histogram This type of histogram a...
10,964
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...
10,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Global Imports Step1: External Package Imports Step2: Tweaking Display Parameters Load default custom.css file from ipython profile Step3: Pandas display parameters Step4: Tweaking color...
Python Code: %pylab inline Explanation: Global Imports End of explanation import os as os import pickle as pickle import pandas as pd print 'changing to source dirctory' os.chdir('../src') import Data.Firehose as FH Explanation: External Package Imports End of explanation from IPython import utils from IPython.displa...
10,966
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross-Validation We follow Rosser et al. and use a maximum-likelihood approach to finding the "best" parameters for the time and space bandwidths. Use a "training" dataset of 180 days For ea...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.collections import numpy as np import shelve import open_cp.network import open_cp.geometry import open_cp.network_hotspot import open_cp.logger open_cp.logger.log_to_true_stdout() import pickle, lzma with lzma.open("input_old.pic.xz", "r...
10,967
Given the following text description, write Python code to implement the functionality described below step by step Description: tsam - Optimal combination of segments and periods for building supply systems Date Step1: Input data Read in time series from testdata.csv with pandas Step2: Create a plot function for a ...
Python Code: %load_ext autoreload %autoreload 2 import copy import os import pandas as pd import matplotlib.pyplot as plt import tsam.timeseriesaggregation as tsam import tsam.hyperparametertuning as tune import tqdm %matplotlib inline Explanation: tsam - Optimal combination of segments and periods for building supply ...
10,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization Methods Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that c...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.io import math import sklearn import sklearn.datasets from opt_utils import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation from opt_utils import compute_cost, predict, predict_dec, plot_decision_boundar...
10,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Functional Expansions OpenMC's general tally system accommodates a wide range of tally filters. While most filters are meant to identify regions of phase space that contribute to a tally, th...
Python Code: %matplotlib inline import openmc import numpy as np import matplotlib.pyplot as plt Explanation: Functional Expansions OpenMC's general tally system accommodates a wide range of tally filters. While most filters are meant to identify regions of phase space that contribute to a tally, there are a special se...
10,970
Given the following text description, write Python code to implement the functionality described below step by step Description: I. Imports Step1: I want to import Vgg16 as well because I'll want it's low-level features Step2: Actually, looks like Vgg's ImageNet weights won't be needed. Step3: II. Load Data Step4: ...
Python Code: import keras import numpy as np from keras.datasets import mnist from keras.optimizers import Adam from keras.models import Sequential from keras.preprocessing import image from keras.layers.core import Dense from keras.layers.core import Lambda from keras.layers.core import Flatten from keras.layers.core ...
10,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Inital Sources Using the sources at 007.20321 +14.87119 and RA = 20 Step1: Read in the two data files. Currently, the *id's are in double format. This is different from the orginial table's...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from astropy.table import Table as tab Explanation: Inital Sources Using the sources at 007.20321 +14.87119 and RA = 20:50:00.91, dec = -00:42:23.8 taken from the NASA/IPAC Infrared Science Archieve on 6/22/17. End of explanation source_...
10,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding a discharge point source to a LEM (Greg Tucker, CSDMS / CU Boulder, fall 2020) This notebook shows how to add one or more discharge point sources to a Landlab-built landscape evolutio...
Python Code: from landlab import RasterModelGrid, imshow_grid from landlab.components import FlowAccumulator import numpy as np Explanation: Adding a discharge point source to a LEM (Greg Tucker, CSDMS / CU Boulder, fall 2020) This notebook shows how to add one or more discharge point sources to a Landlab-built landsca...
10,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Feedback or issues? For any feedback or questions, please open an issue. Vertex SDK for Python Step1: Enter Your Project and GCS Bucket Enter your Project Id in the cell below. Then run the...
Python Code: !pip3 uninstall -y google-cloud-aiplatform !pip3 install google-cloud-aiplatform import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) Explanation: Feedback or issues? For any feedback or questions, please open an issue. Vertex SDK for Python: AutoML Video Action Recognition Exam...
10,974
Given the following text description, write Python code to implement the functionality described below step by step Description: Housekeeping Unit Test This notebook contains a Unit Test for the housekeeping information from the Observatory Simulator. Starting the Observatory Simulator Remember that whenever you power...
Python Code: from tessfpe.dhu.fpe import FPE from tessfpe.dhu.unit_tests import check_house_keeping_voltages fpe1 = FPE(1, debug=False, preload=False, FPE_Wrapper_version='6.1.1') print fpe1.version if check_house_keeping_voltages(fpe1): print "Wrapper load complete. Interface voltages OK." Explanation: Housekeepin...
10,975
Given the following text description, write Python code to implement the functionality described below step by step Description: CS109 Final Project Process Book Background & Motivation Social media and entertainment are such pervasive parts of millennials' lives. We want to study the intersection of these two. Is it ...
Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd import time import json import statsmodels.api as sm from statsmodels.formula.api import glm, ols pd.set_option('display.width', 500) pd.set_optio...
10,976
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic regression Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: Generational Changes As a second example of logistic regression, we'll use data from the Genera...
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/ThinkBayes2/raw/m...
10,977
Given the following text description, write Python code to implement the functionality described below step by step Description: 베르누이 확률 분포 베르누이 시도 결과가 성공(Success) 혹은 실패(Fail) 두 가지 중 하나로만 나오는 것을 베르누이 시도(Bernoulli trial)라고 한다. 예를 들어 동전을 한 번 던져 앞면(H Step1: pmf 메서드를 사용하면 확률 질량 함수(pmf Step2: 시뮬레이션을 하려면 rvs 메서드를 사용한다. St...
Python Code: theta = 0.6 rv = sp.stats.bernoulli(theta) rv Explanation: 베르누이 확률 분포 베르누이 시도 결과가 성공(Success) 혹은 실패(Fail) 두 가지 중 하나로만 나오는 것을 베르누이 시도(Bernoulli trial)라고 한다. 예를 들어 동전을 한 번 던져 앞면(H:Head)이 나오거나 뒷면(T:Tail)이 나오게 하는 것은 베르누이 시도의 일종이다. 베르누이 시도의 결과를 확률 변수(random variable) $X$ 로 나타낼 때는 일반적으로 성공을 정수 1 ($X=1$), 실패를 정수 ...
10,978
Given the following text description, write Python code to implement the functionality described below step by step Description: 데이터의 특성은 분포와 관계가 있다. 모양에 해당하는 부분이 분포다. 예를 들어, 원의 경우 반지름, 사각형의 경우 가로세로 길이가 모양에 해당한다. 그림을 그려서 파악하는 이유는 봉우리가 몇 개인지를 파악하기 위해서 uni-modal(단봉)인지 multi-modal인지 파악하기 위해서 관계의 경우에는 scatter plot이나 다른 모...
Python Code: np.random.seed(0) x = np.random.normal(size=100) x sp.stats.describe(x) pd.Series(x).describe() Explanation: 데이터의 특성은 분포와 관계가 있다. 모양에 해당하는 부분이 분포다. 예를 들어, 원의 경우 반지름, 사각형의 경우 가로세로 길이가 모양에 해당한다. 그림을 그려서 파악하는 이유는 봉우리가 몇 개인지를 파악하기 위해서 uni-modal(단봉)인지 multi-modal인지 파악하기 위해서 관계의 경우에는 scatter plot이나 다른 모형들로 파악하게...
10,979
Given the following text description, write Python code to implement the functionality described below step by step Description: WH Nixalo - 02 Aug 2017 Step1: Aaaahaaaaaaaa. Okay. so the .output parameter for kears.models.Model(..) will take all layers of a model up to and including the layer specified. It does NOT ...
Python Code: import keras from keras.models import Model from keras.layers import Dense, Input, Convolution2D from keras.applications.imagenet_utils import _obtain_input_shape from keras import backend as K input_shape = (224, 224, 3) img_input = Input(shape=input_shape, name='blah-input') # x = Convolution2D(64, 3, 3,...
10,980
Given the following text description, write Python code to implement the functionality described below step by step Description: BERT (from HuggingFace Transformers) for Text Extraction Author Step1: Set-up BERT tokenizer Step2: Load the data Step3: Preprocess the data Go through the JSON file and store every recor...
Python Code: import os import re import json import string import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tokenizers import BertWordPieceTokenizer from transformers import BertTokenizer, TFBertModel, BertConfig max_len = 384 configuration = BertConfig() ...
10,981
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Repeatable splitting </h1> In this notebook, we will explore the impact of different ways of creating machine learning datasets. <p> Repeatability is important in machine learning. If y...
Python Code: from google.cloud import bigquery Explanation: <h1> Repeatable splitting </h1> In this notebook, we will explore the impact of different ways of creating machine learning datasets. <p> Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answ...
10,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-supervised contrastive learning with SimSiam Author Step1: Define hyperparameters Step2: Load the CIFAR-10 dataset Step3: Defining our data augmentation pipeline As studied in SimCLR...
Python Code: from tensorflow.keras import layers from tensorflow.keras import regularizers import tensorflow as tf import matplotlib.pyplot as plt import numpy as np Explanation: Self-supervised contrastive learning with SimSiam Author: Sayak Paul<br> Date created: 2021/03/19<br> Last modified: 2021/03/20<br> Descripti...
10,983
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Meta with Big Data Malaysia Scraping the Big Data Malaysia Facebook group for fun. Profit unlikely. Hello World This is an introductory-level notebook demonstrating how to deal with ...
Python Code: # we need this for later: %matplotlib inline import json INPUT_FILE = "all_the_data.json" with open(INPUT_FILE, "r") as big_data_fd: big_data = json.load(big_data_fd) Explanation: Getting Meta with Big Data Malaysia Scraping the Big Data Malaysia Facebook group for fun. Profit unlikely. Hello World This i...
10,984
Given the following text description, write Python code to implement the functionality described below step by step Description: General Concepts HOW TO RUN THIS FILE Step1: Let's get started with some basic imports Step2: If running in IPython notebooks, you may see a "ShimWarning" depending on the version of Jupyt...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: General Concepts HOW TO RUN THIS FILE: if you're running this in a Jupyter notebook or Google Colab session, you can click on a cell and then shift+Enter to run the cell and automatically select the next cell. Alt+Enter will run a cell and create a new cell ...
10,985
Given the following text description, write Python code to implement the functionality described below step by step Description: 9 defenses Low Bar ALLIANCE selected Audience selected ALLIANCE selected ALLIANCE selected Data structure choices include Step1: Analysis Functions
Python Code: # Object oriented approach, would have to feed csv data into objects # maybe get rid of this and just use library analysis tools class Robot(object): def __init__(self, name, alliance, auto_points, points): self.name = name self.alliance = alliance self.auto_points = auto_points self.points = poin...
10,986
Given the following text description, write Python code to implement the functionality described below step by step Description: .загружаем файлы .json Step1: Смотрим, где именно в файле интересующие нас данные Step2: Считываем нужные нам данные как датафреймы Step3: Создаем в датафреймах отдельные столбцы с данным...
Python Code: path = 'data/Sessions_Page.json' path2 = 'data/Goal1CompletionLocation_Goal1Completions.json' with open(path, 'r') as f: sessions_page = json.loads(f.read()) with open(path2, 'r') as f: goals_page = json.loads(f.read()) Explanation: .загружаем файлы .json End of explanation type (sessions_page) ses...
10,987
Given the following text description, write Python code to implement the functionality described below step by step Description: Issue 26 Step1: Builtin method to highlight clades Step2: Or, use toyplot directly This method is more flexible and you can do just about anything with it. Step3: More examples Things can...
Python Code: import toytree import toyplot # generate a random tree tre = toytree.rtree.unittree(ntips=10, treeheight=100, seed=123) Explanation: Issue 26: highlight clades I've created an early form of an Annotator class object that can be used to add highlights to a toytree drawing. Possible extensions: - apply li...
10,988
Given the following text description, write Python code to implement the functionality described below step by step Description: GaAs-AlAs Bragg Mirror A simple bragg mirror in the near infrared. As a default, this notebook is setup to work with binder. Importing libraries Below we import the library python style, i.e...
Python Code: # importing libraries import numpy as np # numpy import matplotlib.pyplot as plt # matplotlib pyplot import sys # sys to add py_matrix to the path # adding folder containing 1DPyHC to path: by default is the folder for running in binder sys.path.append('/home/main/notebooks') import pyhc a...
10,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC. 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 Licen...
Python Code: from __future__ import division import pandas as pd import numpy as np import json import os,sys import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import numpy as np Explanation: Copyright 2020 Google LLC. Licensed under the Apache License, Version 2...
10,990
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have two arrays A (len of 3.8million) and B (len of 20k). For the minimal example, lets take this case:
Problem: import numpy as np A = np.array([1,1,2,3,3,3,4,5,6,7,8,8]) B = np.array([1,2,8]) C = A[~np.in1d(A,B)]
10,991
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 3 - Sampling with AdaptiveMD Imports Step1: Let's open our tutorial project by its name. If you completed the first examples this should all work out of the box. Step2: Open all c...
Python Code: from adaptivemd import Project Explanation: Tutorial 3 - Sampling with AdaptiveMD Imports End of explanation project = Project('tutorial') Explanation: Let's open our tutorial project by its name. If you completed the first examples this should all work out of the box. End of explanation print(project.file...
10,992
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we mainly utilize extreme gradient boost to improve the prediction model originially proposed in TLE 2016 November machine learning tuotrial. Extreme gradient boost can be ...
Python Code: %matplotlib inline import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import matplotlib.colors as colors import xgboost as xgb import numpy as np from sklearn.metrics import confusion_matrix, f1_score, accuracy...
10,993
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 3</font> Download Step1: While Step2: Pass, Break, Continue Step3: While e For juntos
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 3</font> Download: http://github.com/dsacademybr End of explanation # Usa...
10,994
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation n=np.random.standard_normal? n=np.random.standard_normal n=np.random.randn n=np...
10,995
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing features with MusicExtractor MusicExtractor is a multi-purpose algorithm for music audio feature extraction from files (see the complete list of computed features here). It combine...
Python Code: audiofile = '../../../test/audio/recorded/dubstep.mp3' # This is how the audio we want to process sounds like. import IPython IPython.display.Audio(audiofile) import essentia import essentia.standard as es # Compute all features. # Aggregate 'mean' and 'stdev' statistics for all low-level, rhythm, and tona...
10,996
Given the following text description, write Python code to implement the functionality described below step by step Description: A quick example of the code for generating the mask for the North Atlantic (to be further used with fpost) %matplotlib notebook %load_ext autoreload %autoreload 2 Step1: selecting the NA ma...
Python Code: import sys sys.path.append("../") import pyfesom as pf import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.colors import LinearSegmentedColormap import numpy as np %matplotlib notebook from matplotlib import cm from netCDF4 import Dataset meshID='fArc' # read the mesh m...
10,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear PCA Step1: non linear PCA http
Python Code: #xyz=records[['Latitude','Longitude','Magnitude','Depth/Km','deltaT']].values[1:].T lxyz=xyz.T.copy() lxyz=lxyz[:,2:] lxyz/=lxyz.std(axis=0) "Magnitude,Depth,deltaT" print lxyz.shape l,e,MD=pma.pma(lxyz) X=pma.get_XY(lxyz,e) sns.plt.plot(np.cumsum(l)/np.sum(l),'o-') sns.plt.figure() sns.plt.plot(e[:,:3]) s...
10,998
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 3 Imports Step2: Using interact for animation with data A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 3 Imports End of explanation def soliton(x, t, c, a): Return phi(x, t) for a soliton wave with cons...
10,999
Given the following text description, write Python code to implement the functionality described below step by step Description: Context Reading data from a software version control system can be pretty useful if you want to answer some evolutionary questions like * Who are our main committers to the software? * Are t...
Python Code: with open (r'data/gitlog_aim42.log') as log: [print(line, end='') for line in log.readlines()[:8]] Explanation: Context Reading data from a software version control system can be pretty useful if you want to answer some evolutionary questions like * Who are our main committers to the software? * Are th...