Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
8,600
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer Learning Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea...
Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=...
8,601
Given the following text description, write Python code to implement the functionality described below step by step Description: Collecting Tweets This notebook shows how to collect tweets. For analyzing words you want to collect by search term, but collecting tweets from a specific user is also possible. Step1: Coll...
Python Code: import sys sys.path.append('..') from twords.twords import Twords import matplotlib.pyplot as plt %matplotlib inline import pandas as pd # this pandas line makes the dataframe display all text in a line; useful for seeing entire tweets pd.set_option('display.max_colwidth', -1) twit_mars = Twords() # set p...
8,602
Given the following text description, write Python code to implement the functionality described below step by step Description: Nonequilibrium Switching Free Energy Analysis This notebook is useful for examining the results of nonequilibrium switching calculations performed with the Perses tool. It enables examinatio...
Python Code: import numpy as np import nglview from bokeh.plotting import figure, output_notebook, show from bokeh.layouts import row, column import simtk.unit as unit import mdtraj as md import plotting_tools output_notebook() Explanation: Nonequilibrium Switching Free Energy Analysis This notebook is useful for exami...
8,603
Given the following text description, write Python code to implement the functionality described below step by step Description: Kernel Density Estimation for outlier detection Motivation A common assumption in pattern recognition is that all classes are known. This assumption does not hold in many real-world applicat...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn.neighbors.kde import KernelDensity %matplotlib inline Explanation: Kernel Density Estimation for outlier detection Motivation A common assumption in pattern recognition is that all classes are kn...
8,604
Given the following text description, write Python code to implement the functionality described below step by step Description: # Getting Started with gensim The goal of this tutorial is to get a new user up-and-running with gensim. This notebook covers the following objectives. ## Objectives Installing gensim. Acce...
Python Code: raw_corpus = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relati...
8,605
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
8,606
Given the following text description, write Python code to implement the functionality described below step by step Description: Scraping the web is fun Step1: Let's scrape the daily crime log from Cambridge, Massachusetts! The most powerful web-scraping Python library is lxml... Step2: Wow that's ugly. Wait, can't ...
Python Code: import requests r = requests.get("http://berkeley.edu") r dir(r) r.encoding Explanation: Scraping the web is fun: Do-goodery Making much money Amusing much people End of explanation import lxml.html as LH url = "http://www.cambridgema.gov/cpd/newsandalerts/Archives/detail.aspx?path=%2fsitecore%2fcontent%2f...
8,607
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph attributes can be manipulated through the set_*() and get_*() methods. Step1: Defaults can be set for nodes and edges. Step2: Nodes, edges and subgraphs are added and deleted through...
Python Code: graph.set_fontsize('12') graph.get_fontsize() Explanation: Graph attributes can be manipulated through the set_*() and get_*() methods. End of explanation graph.set_node_defaults(fillcolor='blue', style='filled') graph.get_node_defaults() Explanation: Defaults can be set for nodes and edges. End of explana...
8,608
Given the following text description, write Python code to implement the functionality described below step by step Description: Training at scale with AI Platform Training Service Learning Objectives Step1: Change your project name and bucket name in the cell below if necessary. Step2: Confirm below that the bucket...
Python Code: from google import api_core from google.cloud import bigquery Explanation: Training at scale with AI Platform Training Service Learning Objectives: 1. Learn how to organize your training code into a Python package 1. Train your model using cloud infrastructure via Google Cloud AI Platform Training Serv...
8,609
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 24 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: In this chapter we model systems that involve rotating objects. Rotation Rotation is complicated Ste...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
8,610
Given the following text description, write Python code to implement the functionality described below step by step Description: Options Widgets Herein, we present the widgets that can be used as components in order to assemble higher level widgets, such as the ones presented in Menpo Widgets.ipynb and MenpoFit Widget...
Python Code: from menpowidgets.options import (AnimationOptionsWidget, ChannelOptionsWidget, PatchOptionsWidget, LandmarkOptionsWidget, RendererOptionsWidget, PlotOptionsWidget, LinearModelParametersWidget, TextPrintWidget, FeatureOptionsWidget, ...
8,611
Given the following text description, write Python code to implement the functionality described below step by step Description: <p> <img src="http Step1: <center><img src="https Step2: By convention, you'll find that most people in the SciPy/PyData world will import NumPy using np as an alias Step3: Throughout thi...
Python Code: __AUTHORS__ = {'am': ("Andrea Marino", "andrea.marino@unifi.it",), 'mn': ("Massimo Nocentini", "massimo.nocentini@unifi.it", "https://github.com/massimo-nocentini/",)} __KEYWORDS__ = ['Python', 'numpy', 'numerical', 'data',...
8,612
Given the following text description, write Python code to implement the functionality described below step by step Description: Generating Features from GeoTiff Files From GeoTiff Files available for India over a period of more than 20 years, we want to generate features from those files for the problem of prediction...
Python Code: from osgeo import ogr, osr, gdal import fiona from shapely.geometry import Point, shape import numpy as np import pandas as pd import os import sys import tarfile import timeit Explanation: Generating Features from GeoTiff Files From GeoTiff Files available for India over a period of more than 20 years, we...
8,613
Given the following text description, write Python code to implement the functionality described. Description: Significant Inversions in an Array Function that sorts the input array and returns the number of inversions in the array ; Recursive function that sorts the input array and returns the number of inversions in ...
Python Code: def mergeSort(arr , array_size ) : temp =[0 for i in range(array_size ) ] return _mergeSort(arr , temp , 0 , array_size - 1 )  def _mergeSort(arr , temp , left , right ) : mid , inv_count = 0 , 0 if(right > left ) : mid =(right + left ) // 2 inv_count = _mergeSort(arr , temp , left , mid ...
8,614
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <a href="https Step1: Exercise 1 Step2: Code up your own SVM solution below Step3: Code up your own SVM solution below Step4: Code up your own solution
Python Code: import numpy as np np.random.seed(4242) Explanation: <!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px s...
8,615
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This example demonstrates using a network pretrained on ImageNet for classification. The model used was converted from the VGG_CNN_S model (http Step1: Setup Step2: Define the...
Python Code: !wget https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg_cnn_s.pkl Explanation: Introduction This example demonstrates using a network pretrained on ImageNet for classification. The model used was converted from the VGG_CNN_S model (http://arxiv.org/abs/1405.3531) in Caffe's Model Zoo. For d...
8,616
Given the following text description, write Python code to implement the functionality described below step by step Description: Path Loss Models This notebook illustrates some path loss models. Initializations First we set the Python path and import some libraries. Step1: Now we import some pyphysim stuff Step2: Pa...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot as plt Explanation: Path Loss Models This notebook illustrates some path loss models. Initializations First we set the Python path and import some libraries. End of explanation from pyphysim.channels import pathloss Explanation: Now we imp...
8,617
Given the following text description, write Python code to implement the functionality described below step by step Description: Funciones Una función es una sección de código reutilizable, escrita para realizar una tarea específica en un programa. ¿Por qué son útiles las funciones? Fíjate en los siguientes ejemplos....
Python Code: # necesito calcular el cuadrado de un número # defino una variable asignándole el valor 6 n = 6 # calculo el cuadrado y lo imprimo por pantalla cuadrado = n**2 print(cuadrado) # ahora me piden que calcule otro cuadrado, en este caso de 8 # repito el proceso n = 8 cuadrado = n**2 print(cuadrado) Explanation...
8,618
Given the following text description, write Python code to implement the functionality described below step by step Description: ABU量化系统使用文档 <center> <img src="./image/abu_logo.png" alt="" style="vertical-align Step1: 与之前章节一样,本节示例的相关性分析只限制在abupy内置沙盒数据中,和上一节一样首先将内置沙盒中美股,A股,港股, 比特币,莱特币,期货市场中的symbol都列出来,然后组成训练集和...
Python Code: # 基础库导入 from __future__ import print_function from __future__ import division import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,...
8,619
Given the following text description, write Python code to implement the functionality described below step by step Description: Station Plot with Layout Make a station plot, complete with sky cover and weather symbols, using a station plot layout built into MetPy. The station plot itself is straightforward, but there...
Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import pandas as pd from metpy.calc import get_wind_components from metpy.cbook import get_test_data from metpy.plots import (add_metpy_logo, simple_layout, StationPlot, StationPlotLayout,...
8,620
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.0 Load data from http Step1: 1.2 Calculate Actual Profit Step2: 1.3 Load data from 'Calories' worksheet and plot Step3: 1.4 add calorie data to sales worksheet Step4: 1.5 pivot table S...
Python Code: # code written in python_3. (for py_2.7 users some changes may be required) import pandas # load pandas dataframe lib import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np # find path to your Concessions.xlsx # df = short for dataframe == excel worksheet # zero indexing in python, so f...
8,621
Given the following text description, write Python code to implement the functionality described below step by step Description: Now that we have created and saved a configuration file, let’s read it back and explore the data it holds. Step1: Please note that default values have precedence over fallback values. For i...
Python Code: config = configparser.ConfigParser() config.sections() config.read('example.ini') config.sections() 'bitbucket.org' in config 'bytebong.com' in config config['bitbucket.org']['User'] config['DEFAULT']['Compression'] topsecret = config['topsecret.server.com'] topsecret['ForwardX11'] topsecret['Port'] for ke...
8,622
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Python PCA - Plotting Explained Variance Ratio with Matplotlib
Python Code:: import matplotlib.pyplot as plt plt.figure(figsize=(10,6)) plt.bar(x=range(0,len(X_train.columns)), height=pca.explained_variance_ratio_, tick_label=X_train.columns) plt.title('Explained Variance Ratio') plt.ylabel('Explained Variance Ratio') plt.xlabel('Component') plt.show()
8,623
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
8,624
Given the following text description, write Python code to implement the functionality described below step by step Description: Heatmap The HeatMap mark represents a 2d matrix of values as a color image. It can be used to visualize a 2d function, or a grayscale image for instance. HeatMap is very similar to the GridH...
Python Code: import numpy as np from bqplot import Figure, LinearScale, ColorScale, Color, Axis, HeatMap, ColorAxis from ipywidgets import Layout Explanation: Heatmap The HeatMap mark represents a 2d matrix of values as a color image. It can be used to visualize a 2d function, or a grayscale image for instance. HeatMap...
8,625
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Customization basics Step2: Import TensorFlow To get started, import the tensorflow module. As of TensorFlow 2.0, eager execution is turned on...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
8,626
Given the following text description, write Python code to implement the functionality described below step by step Description: 레버리지와 아웃라이어 레버리지 (Leverage) 개별적인 데이터 표본이 회귀 분석 결과에 미치는 영향은 레버리지(leverage)분석을 통해 알 수 있다. 레버리지는 target value $y$가 예측된(predicted) target $\hat{y}$에 미치는 영향을 나타낸 값이다. self-influence, self-sensiti...
Python Code: from sklearn.datasets import make_regression X0, y, coef = make_regression(n_samples=100, n_features=1, noise=20, coef=True, random_state=1) # add high-leverage points X0 = np.vstack([X0, np.array([[4], [3]])]) X = sm.add_constant(X0) y = np.hstack([y, [300, 150]]) plt.scatter(X0, y) plt.show() model = sm....
8,627
Given the following text description, write Python code to implement the functionality described below step by step Description: Run the CCF analysis You should have already cross-correlated all your spectra against a suitable model using Search.py. This notebook goes through the shifting and subtracting of the averag...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import CombineCCFs import numpy as np from astropy import units as u, constants from HelperFunctions import Gauss, integral import os import lmfit import emcee import triangle from scipy.interpolate import Interpol...
8,628
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the SIAF class The Science Instrument Aperture File, or SIAF, provides approximate conversions of sky positions to detector positions in support of operations. (More sophisticated corr...
Python Code: %pylab inline --no-import-all plt.style.use('ggplot') Explanation: Using the SIAF class The Science Instrument Aperture File, or SIAF, provides approximate conversions of sky positions to detector positions in support of operations. (More sophisticated corrections, e.g. for correcting and analyzing science...
8,629
Given the following text description, write Python code to implement the functionality described below step by step Description: OpenMP example In this example we illustrate how OpenMP can be used to speedup the calculation of the likelihood. First we set the number of openmp threads. This is done via an environmental...
Python Code: import os os.environ['OMP_NUM_THREADS'] = '4' Explanation: OpenMP example In this example we illustrate how OpenMP can be used to speedup the calculation of the likelihood. First we set the number of openmp threads. This is done via an environmental variable called OMP_NUM_THREADS. In this example we set t...
8,630
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: 编写自己的回调函数 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Keras 回调函数概述 所有回调函数都将 keras.callb...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
8,631
Given the following text description, write Python code to implement the functionality described below step by step Description: In this short tutorial, we will compute the static connectivity of the EEG singals. Load data Step1: Static connectivity As a first example, we are going to compute the static connectivity ...
Python Code: import numpy as np import scipy from scipy import io eeg = np.load("data/eeg_eyes_opened.npy") num_trials, num_channels, num_samples = np.shape(eeg) eeg_ts = np.squeeze(eeg[0, :, :]) Explanation: In this short tutorial, we will compute the static connectivity of the EEG singals. Load data End of explanatio...
8,632
Given the following text description, write Python code to implement the functionality described below step by step Description: Control Structures Simple for loop Write a for loop which iterates over the list of breakfast items "sausage", "eggs", "bacon" and "spam" and prints out the name of item Step1: Write then a...
Python Code: breakfast = ["sausage", "eggs", "bacon", "spam"] for item in breakfast: print(item) Explanation: Control Structures Simple for loop Write a for loop which iterates over the list of breakfast items "sausage", "eggs", "bacon" and "spam" and prints out the name of item End of explanation squares = [] for ...
8,633
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple Kernel Learning By Saurabh Mahindre - <a href="https Step1: Introduction <em>Multiple kernel learning</em> (MKL) is about using a combined kernel i.e. a kernel consisting of a line...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import shogun as sg %matplotlib inline SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') Explanation: Multiple Kernel Learning By Saurabh Mahindre - <a href="https://github.com/Saurabh7">github.com/Saurabh7</a> This notebook is about ...
8,634
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="static/pybofractal.png" alt="Pybonacci" style="width Step1: Note Step2: The declaration of a model is also required. The use of the name <span style="color Step3: We declare the...
Python Code: !cat abstract1.py Explanation: <img src="static/pybofractal.png" alt="Pybonacci" style="width: 200px;"/> <img src="static/cacheme_logo.png" alt="CAChemE" style="width: 300px;"/> 1. Pyomo Overview Note: Adapted from https://github.com/Pyomo/PyomoGettingStarted, by William and Becca Hart 1.1 Mathematical Mod...
8,635
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and resampling data This tutorial covers filtering and resampling, and gives examples of how filtering can be used for artifact repair. Step1: Background on filtering A filter...
Python Code: import os import numpy as np import matplotlib.pyplot as plt 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) ...
8,636
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 2 Work on this before the next lecture on 24 April. We will talk about questions, comments, and solutions during the exercise after the third lecture. Please do form study groups! W...
Python Code: %config InlineBackend.figure_format='retina' %matplotlib inline import numpy as np np.random.seed(123) import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (8, 8) plt.rcParams["font.size"] = 14 from sklearn.utils import check_random_state Explanation: Exercise 2 Work on this before the next lec...
8,637
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook Tour Step1: The Jupyter Notebook is a web-based application that enables users to create documents that combine live code wth narrative next, equations, images, visualizations and ...
Python Code: from IPython.display import display, Image, HTML from talktools import website, nbviewer Explanation: Notebook Tour End of explanation 2+2 import math math.atan? Explanation: The Jupyter Notebook is a web-based application that enables users to create documents that combine live code wth narrative next, eq...
8,638
Given the following text description, write Python code to implement the functionality described below step by step Description: Netscan Here is a sample of some the capabilities of the netscan library. Step1: Get host info On macOS or Linux, GetHostName should be able to resolve a computer's IP address to a hostname...
Python Code: from __future__ import print_function from netscan.lib import WhoIs, GetHostName, MacLookup, Commands import pprint as pp Explanation: Netscan Here is a sample of some the capabilities of the netscan library. End of explanation print(GetHostName('192.168.1.13').name) print(GetHostName('127.0.0.1').name) Ex...
8,639
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning word embeddings - word2vec - Saurabh Mathur The aim of this experiment is to use the algorithm developed by Tomas Mikolov et al. to learn high quality vector representations of text...
Python Code: import tensorflow as tf Explanation: Learning word embeddings - word2vec - Saurabh Mathur The aim of this experiment is to use the algorithm developed by Tomas Mikolov et al. to learn high quality vector representations of text. The skip-gram model Given, a sequence of words $ w_1, w_2, .., w_T $, predict ...
8,640
Given the following text description, write Python code to implement the functionality described below step by step Description: Sliding Windows Many applications require computations on sliding windows of streams. A sliding window is specified by a window size and a step size, both of which are positive integers. Sli...
Python Code: import os import sys sys.path.append("../") from IoTPy.core.stream import Stream, run from IoTPy.agent_types.op import map_window from IoTPy.helper_functions.recent_values import recent_values def example(): x, y = Stream(), Stream() map_window(func=sum, in_stream=x, out_stream=y, window_size=2, st...
8,641
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 2 Step1: A function in PyRTL is nothing special -- it just so happens that the statements it encapsulate tell PyRTL to build some hardware. Step2: If we call one_bit_add above with...
Python Code: import pyrtl pyrtl.reset_working_block() Explanation: Example 2: A Counter with Ripple Carry Adder. This next example shows how you make stateful things with registers and more complex hardware structures with functions. We generate a 3-bit ripple carry adder building off of the 1-bit adder from the prio...
8,642
Given the following text description, write Python code to implement the functionality described below step by step Description: Export epochs to Pandas DataFrame In this example the pandas exporter will be used to produce a DataFrame object. After exploring some basic features a split-apply-combine work flow will be ...
Python Code: # Author: Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne import matplotlib.pyplot as plt import numpy as np from mne.datasets import sample print(__doc__) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = dat...
8,643
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Numpy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of Numpy Step2: Built-in Me...
Python Code: import numpy as np Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> <center>Copyright Pierian Data 2017</center> <center>For more information, visit us at www.pieriandata.com</center> NumPy NumPy (or Numpy) is a Linear Algebra Library for Python, the reason it i...
8,644
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.1 - Calculer un chi 2 sur un tableau de contingence $\chi_2$ et tableau de contingence, avec numpy, avec scipy ou sans. Step1: formule Le test du $\chi_2$ (wikipedia) sert à comparer deu...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.1 - Calculer un chi 2 sur un tableau de contingence $\chi_2$ et tableau de contingence, avec numpy, avec scipy ou sans. End of explanation import numpy M = numpy.array([[4, 5, 2, 1], [6, 3, 1, 7], ...
8,645
Given the following text description, write Python code to implement the functionality described below step by step Description: This document demonstrate how to use the library to define a "density dependent population process" and to compute its mean-field approximation and refined mean-field approximation Step1: E...
Python Code: # To load the library import rmftool as rmf import importlib importlib.reload(rmf) # To plot the results import numpy as np import matplotlib.pyplot as plt # %matplotlib inline %matplotlib notebook Explanation: This document demonstrate how to use the library to define a "density dependent population proce...
8,646
Given the following text description, write Python code to implement the functionality described below step by step Description: Trajectory equations Step1: The equation of motion Step2: For the case of a uniform magnetic field along the $z$-axis Step3: Assuming $E_z = 0$ and $E_y = 0$ Step4: Motion is uniform al...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from sympy import * init_printing() Ex, Ey, Ez = symbols("E_x, E_y, E_z") Bx, By, Bz, B = symbols("B_x, B_y, B_z, B") x, y, z = symbols("x, y, z") vx, vy, vz, v = symbols("v_x, v_y, v_z, v") t = symbols("t") q, m = symbols("q, m") c, eps0 = symbols("c, eps...
8,647
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Dimensionality Reduction Step1: Introducing Principal Component Analysis Princ...
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('seaborn') Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Dimensionality R...
8,648
Given the following text description, write Python code to implement the functionality described below step by step Description: If I plan to run the scorer every batch to select loans, I should have a minimum score that a loan must receive to even be considered for investing in, and the remaining loans can be selecte...
Python Code: import modeling_utils.data_prep as data_prep from sklearn.externals import joblib import time platform = 'lendingclub' store = pd.HDFStore( '/Users/justinhsi/justin_tinkering/data_science/lendingclub/{0}_store.h5'. format(platform), append=True) Explanation: If I plan to run the scorer every ba...
8,649
Given the following text description, write Python code to implement the functionality described below step by step Description: Download the list of occultation periods from the MOC at Berkeley. Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is onl...
Python Code: fname = io.download_occultation_times(outdir='../data/') print(fname) Explanation: Download the list of occultation periods from the MOC at Berkeley. Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is only really useful for observation pl...
8,650
Given the following text description, write Python code to implement the functionality described below step by step Description: Training on an Advanced Standard CNN Architecture https Step1: Preparation Step2: Uncomment next three cells if you want to train on augmented image set Otherwise Overfitting can not be av...
Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pylab as plt import numpy as np from distutils.version import StrictVersion import sklearn print(sklearn.__version__) assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1') import tensorflow ...
8,651
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Nearest Neighbors (KNN) by Chiyuan Zhang and S&ouml;ren Sonnenburg This notebook illustrates the <a href="http Step1: Let us plot the first five examples of the train data (first row) and...
Python Code: import numpy as np import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import loadmat, savemat from numpy import random from os import path import matplotlib.pyplot as plt %matplotlib inline import shogun as sg mat = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multicl...
8,652
Given the following text description, write Python code to implement the functionality described below step by step Description: Screenshots and Movies with WebGL One can use the REBOUND WebGL ipython widget to capture screenshots of a simualtion. These screenshots can then be easily compiled into a movie. The widget ...
Python Code: import rebound sim = rebound.Simulation() sim.add(m=1) # add a star for i in range(10): sim.add(m=1e-3,a=0.4+0.1*i,inc=0.03*i,omega=5.*i) # Jupiter mass planets on close orbits sim.move_to_com() # Move to the centre of mass frame w = sim.getWidget() w Explanation: Screenshots and Movies with WebGL One ...
8,653
Given the following text description, write Python code to implement the functionality described below step by step Description: Stockmarket analysis with pmdarima This example follows the post on Towards Data Science (TDS), demonstrating the use of pmdarima to simplify time series analysis. Step1: Import the data pm...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import pmdarima as pm print(f"Using pmdarima {pm.__version__}") Explanation: Stockmarket analysis with pmdarima This example follows the post on Towards Data Science (TDS), demonstrating the use of pmdarima to simpl...
8,654
Given the following text description, write Python code to implement the functionality described below step by step Description: Source Step1: Elements Are Lists Step2: Attributes Are Dictonaries Step3: Searching Step4: Generating XML
Python Code: #import lxml.etree as etree try: from lxml import etree as etree except ImportError: import xml.etree.ElementTree as etree tree = etree.parse('feed.xml') root = tree.getroot() root Explanation: Source : Dive Into Python - Chapter 12 XML by Mark Pilgrim XML overview XML is a generalized way of descr...
8,655
Given the following text description, write Python code to implement the functionality described below step by step Description: ZPIC Python interface This notebook illustrates the use of the ZPIC Python interface to run a simulation and save the results to disk. Calling ZPIC from Python requires importing the appropr...
Python Code: import em1d Explanation: ZPIC Python interface This notebook illustrates the use of the ZPIC Python interface to run a simulation and save the results to disk. Calling ZPIC from Python requires importing the appropriate ZPIC module. For this example we will be using the EM1D code, so we need to import the ...
8,656
Given the following text description, write Python code to implement the functionality described below step by step Description: Какво е "цикъл"? В програмирането често се налага многократно изпълнение на дадена последователност от операции. Цикъл (loop) е основна конструкция в програмирането, която позволява многокра...
Python Code: counter = 1 while counter <= 10: print(counter) counter = counter + 1 print("end") Explanation: Какво е "цикъл"? В програмирането често се налага многократно изпълнение на дадена последователност от операции. Цикъл (loop) е основна конструкция в програмирането, която позволява многократно изпъ...
8,657
Given the following text description, write Python code to implement the functionality described below step by step Description: Vehicle Data Data1.txt Dies sind die Werte aus der Datei "data1.txt". Hierbei hatten wir einen folgende Startwerte Step1: Da wir nun die entsprechenden Werte in numpy importiert haben, könn...
Python Code: #Create Lists time = [233.32,198.92,184.7,168.18,148.22,138.88,151.76,127.48,119.12,115.24,110.7,104.28,105.52,109.2,120.7401,147.027] motorTorque = [100,110,121,133.1,146.41,161.051,161.051,177.1561,194.8717,214.3589,235.7948,259.3743,285.3117,313.8429,345.2272,379.74992] print(time) print('elements in ti...
8,658
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport,...
8,659
Given the following text description, write Python code to implement the functionality described below step by step Description: Halo Scattering v1 -- Mainly in the context of the FRB 181112 paper Step1: Kolmogorov estimate Equation 1 of Prochaska et al. 2019 by JP Macquart Step2: $\tau = 1 $ms, $z_{\rm FRB} = 1$, $...
Python Code: # imports import numpy as np from importlib import reload from astropy import units from astropy import constants from frb import turb_scattering as frb_scatt Explanation: Halo Scattering v1 -- Mainly in the context of the FRB 181112 paper End of explanation reload(frb_scatt) z_FRB = 0.4755 z_halo = 0.367 ...
8,660
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Process Regression in Pytorch Thomas Viehmann, &#116;&#118;&#64;&#108;&#101;&#114;&#110;&#97;&#112;&#112;&#97;&#114;&#97;&#116;&#46;&#100;&#101; Modelled after GPFlow Regression not...
Python Code: from matplotlib import pyplot %matplotlib inline import IPython import torch import numpy import sys, os sys.path.append(os.path.join(os.getcwd(),'..')) pyplot.style.use('ggplot') import candlegp import candlegp.training.hmc Explanation: Gaussian Process Regression in Pytorch Thomas Viehmann, &#116;&#118;&...
8,661
Given the following text description, write Python code to implement the functionality described below step by step Description: Todo Step1: Rel risk. P(gender|misaligned)/P(gender) What proportion of the misaligned dataset is about women? For each gender, what proportion of the each misalignment group do the represe...
Python Code: bigdf = pandas.read_csv('/media/notconfusing/9d9b45fc-55f7-428c-a228-1c4c4a1b728c/home/maximilianklein/snapshot_data/2016-01-03/gender-index-data-2016-01-03.csv') gender_qid_df = bigdf[['qid','gender']] def map_gender(x): if isinstance(x,float): return 'no gender' else: gen = x.spli...
8,662
Given the following text description, write Python code to implement the functionality described below step by step Description: Data SITREP redshiftzero, January 26, 2017 We've been collecting traces from crawling onion services, this notebook contains a brief SITREP of the status of the data collection. Step1: Numb...
Python Code: import os import pandas as pd import sqlalchemy import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') with open(os.environ["PGPASS"], "rb") as f: content = f.readline().decode("utf-8").replace("\n", "").split(":") engine = sqlalchemy.create_engine("postgresql:...
8,663
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: Local text binary classification model for online prediction <...
8,664
Given the following text description, write Python code to implement the functionality described below step by step Description: FAQ This document will address frequently asked questions not addressed in other pages of the documentation. How do I install cobrapy? Please see the INSTALL.rst file. How do I cite cobrapy?...
Python Code: from cobra.io import load_model model = load_model("iYS1720") for metabolite in model.metabolites: metabolite.id = f"test_{metabolite.id}" try: model.metabolites.get_by_id(model.metabolites[0].id) except KeyError as e: print(repr(e)) Explanation: FAQ This document will address frequently asked ...
8,665
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
8,666
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-hr5', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-HR5 Topic: Ocean Sub-Topics: Timestepping Framewo...
8,667
Given the following text description, write Python code to implement the functionality described below step by step Description: Modifying Rates Sometimes we want to change the nuclei involved in rates to simplify our network. Currently, pynucastro supports changing the products. Here's an example. Step1: We want t...
Python Code: import pynucastro as pyna reaclib_library = pyna.ReacLibLibrary() Explanation: Modifying Rates Sometimes we want to change the nuclei involved in rates to simplify our network. Currently, pynucastro supports changing the products. Here's an example. End of explanation filter = pyna.RateFilter(reactants=[...
8,668
Given the following text description, write Python code to implement the functionality described below step by step Description: _ doesn't look like much, but as part of a name in Python it has a surprising amount of different meanings. Make names more readable We all know that we should use good names. This often mak...
Python Code: def spam(a, _, b): return a + b spam(1, 2, 3) Explanation: _ doesn't look like much, but as part of a name in Python it has a surprising amount of different meanings. Make names more readable We all know that we should use good names. This often makes it necessary to use more than one word to describe ...
8,669
Given the following text description, write Python code to implement the functionality described below step by step Description: Video using the Base Overlay The PYNQ-Z1 board contains a HDMI input port, and a HDMI output port connected to the FPGA fabric of the Zynq® chip. This means to use the HDMI ports, HDMI contr...
Python Code: from pynq import Overlay from pynq.drivers.video import HDMI # Download bitstream Overlay("base.bit").download() # Initialize HDMI as an input device hdmi_in = HDMI('in') Explanation: Video using the Base Overlay The PYNQ-Z1 board contains a HDMI input port, and a HDMI output port connected to the FPGA fab...
8,670
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License") Step1: On Variational Bounds of Mutual Information Ben Poole, Sherjil Ozair, A&auml;ron van den Oor...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
8,671
Given the following text description, write Python code to implement the functionality described below step by step Description: Scapy in 15 minutes (or longer) Guillaume Valadon & Pierre Lalet Scapy is a powerful Python-based interactive packet manipulation program and library. It can be used to forge or decode packe...
Python Code: send(IP(dst="1.2.3.4")/TCP(dport=502, options=[("MSS", 0)])) Explanation: Scapy in 15 minutes (or longer) Guillaume Valadon & Pierre Lalet Scapy is a powerful Python-based interactive packet manipulation program and library. It can be used to forge or decode packets for a wide number of protocols, send the...
8,672
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据科学 数据科学问题解决流程 workflow stage 问题定义 获取训练和测试数据 数据清洗 预处理 分析数据 建模 预测 解决问题 可视化解决问题流程 提交结果到Kaggle workflow 七大目标 数据科学workflow解决七大问题 1. 分类 1. 相关性 发现特征和结果之前的相关性 或者发现特征之前的相关性 1. 转换 建模阶段根据模型的不同可能需要将...
Python Code: # 数据分析和预处理 import pandas as pd import numpy as np import random as rnd # 数据可视化 import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # 机器学习算法 from sklearn.linear_model import LogisticRegression # logstic回归 from sklearn.linear_model import Perceptron # 感知机 from sklearn.linear_model impor...
8,673
Given the following text description, write Python code to implement the functionality described. Description: Search , insert and delete in a sorted array function to implement binary search ; low + ( high - low ) / 2 ; Driver program to check above functions Let us search 3 in below array
Python Code: def binarySearch(arr , low , high , key ) : mid =(low + high ) / 2 if(key == arr[int(mid ) ] ) : return mid  if(key > arr[int(mid ) ] ) : return binarySearch(arr ,(mid + 1 ) , high , key )  if(key < arr[int(mid ) ] ) : return binarySearch(arr , low ,(mid - 1 ) , key )  return 0  a...
8,674
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', 'test-institute-3', 'sandbox-1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: TEST-INSTITUTE-3 Source ID: SANDBOX-1 Topic: Atmos Sub-Topics: Dy...
8,675
Given the following text description, write Python code to implement the functionality described below step by step Description: MLE with Normal distribution Step1: Draw normal density $$f\left(y_{i};\mu,\sigma\right)=\frac{1}{\sqrt{2\pi\sigma^{2}}}\exp\left(-\frac{\left(y_{i}-\mu\right)^{2}}{2\sigma^{2}}\right)$$ St...
Python Code: import numpy as np import matplotlib.pylab as plt import seaborn as sns np.set_printoptions(precision=4, suppress=True) sns.set_context('notebook') %matplotlib inline Explanation: MLE with Normal distribution End of explanation theta = [[0., 1.], [.5, .5], [-.25, 2.]] f = lambda x, mu, sigma: 1 / np.sqrt(2...
8,676
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2 Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, drop the database you creat...
Python Code: import pg8000 conn = pg8000.connect(database="homework2") Explanation: Homework 2: Working with SQL (Data and Databases 2016) This homework assignment takes the form of an IPython Notebook. There are a number of exercises below, with notebook cells that need to be completed in order to meet particular crit...
8,677
Given the following text description, write Python code to implement the functionality described below step by step Description: SVN Reports Dashboard Reporting import/upload pipelines Import Libraries Libraries necessary to parse through each dashboard Step1: Parametrization Adding parameters for Papermill Step2: S...
Python Code: import datetime from IPython.display import display, Markdown, Latex import json import numpy as np import pandas as pd Explanation: SVN Reports Dashboard Reporting import/upload pipelines Import Libraries Libraries necessary to parse through each dashboard End of explanation site: str Explanation: Paramet...
8,678
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Unicode 文字列 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: tf.string データ型 標準的な TensorFlow ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
8,679
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional variational autoencoder with PyMC3 and Keras In this document, I will show how autoencoding variational Bayes (AEVB) works in PyMC3's automatic differentiation variational infe...
Python Code: #!pip install --upgrade git+https://github.com/Theano/Theano.git#egg=Theano #!pip install --upgrade keras #!pip install --upgrade pymc3 #!conda install -y mkl-service %autosave 0 %matplotlib inline import sys, os os.environ['KERAS_BACKEND'] = 'theano' from theano import config config.floatX = 'float32' con...
8,680
Given the following text description, write Python code to implement the functionality described below step by step Description: ¿Cómo vibra un tambor cuando lo golpeas? Analizar el problema de la membrana vibrante permite entender el funcionamiento de instrumentos de percusión tales como los tambores, timbales e incl...
Python Code: # Importamos todas las librerías que usaremos. Explicación... %matplotlib inline import matplotlib.pyplot as plt from scipy import special import numpy as np from ipywidgets import * # Graficamos funciones de Bessel de orden n = 0,1,...,4 r = np.linspace(0, 10,100) for n in range(5): plt.plot(r, specia...
8,681
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Given a pandas DataFrame, how does one convert several binary columns (where 0 denotes the value exists, 1 denotes it doesn't) into a single categorical column?
Problem: import pandas as pd df = pd.DataFrame({'A': [0, 1, 1, 1, 0, 1], 'B': [1, 0, 1, 1, 1, 0], 'C': [1, 1, 0, 1, 1, 1], 'D': [1, 1, 1, 0, 1, 1]}) df["category"] = df.idxmin(axis=1)
8,682
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Python and MySQL tutorial </center> <center> Author Step1: Calculator Step2: Strings Step3: show ' and " in a string Step4: span multiple lines Step5: slice and index Step6: I...
Python Code: width = 20 height = 5*9 width * height Explanation: <center> Python and MySQL tutorial </center> <center> Author: Cheng Nie </center> <center> Check chengnie.com for the most recent version </center> <center> Current Version: Feb 18, 2016</center> Python Setup Since most students in this class use Windows ...
8,683
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 05 Step1: Define a class called SOM. The constructor builds a grid of nodes, and also defines some helper ops Step2: Time to use our newfound powers. Let's test it out on some data
Python Code: %matplotlib inline import tensorflow as tf import numpy as np Explanation: Ch 05: Concept 03 Self-organizing map Import TensorFlow and NumPy: End of explanation class SOM: def __init__(self, width, height, dim): self.num_iters = 100 self.width = width self.height = height ...
8,684
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 2 Step1: Example 1 Step2: Example 2 Step3: Example 3 Step4: Example 4 Step5: Example 5 Step6: Example 6
Python Code: # Import relevant modules %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import healpy as hp from NPTFit import create_mask as cm # Module for creating masks Explanation: Example 2: Creating Masks In this example we show how to create masks using create_mask.py. Often it is conven...
8,685
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifying Risky P2P Loans Abstract The prevalence of a global Peer-to-Peer (P2P) economy, coupled with the recent deregulation of financial markets, has lead to the widespread adoption of ...
Python Code: from IPython.display import display from IPython.core.display import HTML import warnings warnings.filterwarnings('ignore') import os if os.getcwd().split('/')[-1] == 'notebooks': os.chdir('../') import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as ...
8,686
Given the following text description, write Python code to implement the functionality described below step by step Description: TODO Step1: Коэффициент для учета вклада гелия в массу газа (см. Notes) Step2: Для большой оси Step3: Для случая бесконечного тонкого диска Step4: Два других механизма из http Step5: Hu...
Python Code: %run ../../utils/load_notebook.py from instabilities import * import numpy as np Explanation: TODO: сделать так, чтобы можно было импортировать End of explanation He_coeff = 1.34 def flat_end(argument): '''декоратор для того, чтобы продолжать функцию на уровне последнего значения''' def real_decora...
8,687
Given the following text description, write Python code to implement the functionality described below step by step Description: JSON examples and exercise get familiar with packages for dealing with JSON study examples with JSON strings and files work on exercise to be completed and submitted reference Step1: impo...
Python Code: import pandas as pd Explanation: JSON examples and exercise get familiar with packages for dealing with JSON study examples with JSON strings and files work on exercise to be completed and submitted reference: http://pandas.pydata.org/pandas-docs/stable/io.html#io-json-reader data source: http://jsonstud...
8,688
Given the following text description, write Python code to implement the functionality described below step by step Description: A Recursive Implementation of Minimax This notebook implements the minimax algorithm in a pure form, i.e. it does not employ any memoization techniques. In order to have some variation in ou...
Python Code: import random random.seed(1) Explanation: A Recursive Implementation of Minimax This notebook implements the minimax algorithm in a pure form, i.e. it does not employ any memoization techniques. In order to have some variation in our games, we use random numbers to choose between different optimal moves. E...
8,689
Given the following text description, write Python code to implement the functionality described below step by step Description: Caso de uso 1 - Validación, transformación y harvesting con el catálogo del Ministerio de Justicia Caso 1 Step1: Declaración de variables y paths Step2: Validación del archivo xlsx y trans...
Python Code: import arrow import os, sys sys.path.insert(0, os.path.abspath("..")) from pydatajson import DataJson #lib y clase from pydatajson.readers import read_catalog # lib, modulo ... metodo Lle el catalogo -json o xlsx o (local o url) dicc- y lo transforma en un diccionario de python from pydatajson.writers impo...
8,690
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: モジュール、レイヤー、モデルの概要 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: TensorFlow におけるモデルとレイヤーの定...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
8,691
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: What is an efficient way of splitting a column into multiple rows using dask dataframe? For example, let's say I have a csv file which I read using dask to produce the following das...
Problem: import pandas as pd df = pd.DataFrame([["A", "Z-Y"], ["B", "X"], ["C", "W-U-V"]], index=[1,2,3], columns=['var1', 'var2']) def g(df): return df.join(pd.DataFrame(df.var2.str.split('-', expand=True).stack().reset_index(level=1, drop=True),columns=['var2 '])).\ drop('var2',1).rename(columns=str.strip...
8,692
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Authentication Step2: Install the h5py to prepare sample dataset, and the grpcio-tools for querying against the index. Step3: Restart...
Python Code: PROJECT_ID = "<your_project_id>" # @param {type:"string"} NETWORK_NAME = "ucaip-haystack-vpc-network" # @param {type:"string"} PEERING_RANGE_NAME = "ucaip-haystack-range" # Create a VPC network ! gcloud compute networks create {NETWORK_NAME} --bgp-routing-mode=regional --subnet-mode=auto --project={PROJE...
8,693
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch 02 Step1: The moving average is defined as follows Step2: Here's what we care to visualize Step3: Time to compute the moving averages. We'll also run the merged op to track how the val...
Python Code: import tensorflow as tf import numpy as np raw_data = np.random.normal(10, 1, 100) Explanation: Ch 02: Concept 08 Using TensorBoard TensorBoard is a great way to visualize what's happening behind the code. In this example, we'll loop through some numbers to improve our guess of the average value. Then we ...
8,694
Given the following text description, write Python code to implement the functionality described below step by step Description: Grove Gesture Example This example shows how to use the Grove gesture sensor on the board. The gesture sensor can detect 10 gestures as follows Step1: 1. Instantiate the sensor object Step...
Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Grove Gesture Example This example shows how to use the Grove gesture sensor on the board. The gesture sensor can detect 10 gestures as follows: | Raw value read by sensor | Gesture | |-----------------------...
8,695
Given the following text description, write Python code to implement the functionality described. Description: Sum of the series 1 + ( 1 + 2 ) + ( 1 + 2 + 3 ) + ( 1 + 2 + 3 + 4 ) + ... ... + ( 1 + 2 + 3 + 4 + ... + n ) Function to find sum of series ; Driver Code
Python Code: def sumOfSeries(n ) : return sum([ i *(i + 1 ) / 2 for i in range(1 , n + 1 ) ] )  if __name__== "__main __": n = 10 print(sumOfSeries(n ) ) 
8,696
Given the following text description, write Python code to implement the functionality described below step by step Description: ClarityViz Tutorial Overview claritybase Step1: 2) local histogram equilization local histogram equilization is the process of enhancing low contrast images, and makes the pixel values easi...
Python Code: from clarityviz import claritybase token = 'Fear199' source_directory = '/cis/home/alee/claritycontrol/code/data/raw' # Initialize the claritybase object, the initial basis for all operations. # After you initialize with a token and source directory, a folder will be created in your current directory # wit...
8,697
Given the following text description, write Python code to implement the functionality described below step by step Description: Temporary notebook to get the parameters for the MICE sims for the data ismael sent me. Step1: mean number of central/satellites per bin. read with pd.read_csv(‘hod_redmagicMICE.csv’, sep='...
Python Code: import pandas as pd import numpy as np #fit given by Andres #CENTRALS def f_cen(logmhalo,logmmin,siglogm,fmaxcen,fmincen,k,logmdrop): ncen = 0.5*( 1. + ss.erf((logmhalo[0,:] - logmmin)/siglogm) ) ncen = fmaxcen * ncen ncen = ncen * (1.0 - (1.0-fmincen/fmaxcen)/(1.0 + 10**((2.0/k)*(logmha...
8,698
Given the following text description, write Python code to implement the functionality described below step by step Description: Survival Analysis Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: This chapter introduces "survival analysis", which is a set of statistical methods used to answer...
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 from os.path import basename, exists def download(url): filename = basename(url) if not exists(...
8,699
Given the following text description, write Python code to implement the functionality described below step by step Description: Load the relevant libraries Step1: set the stage for data visualization Step2: Load the dataset and make a copy of it Step3: List all the variables in the dataset Step4: Data standardisa...
Python Code: import pandas as pd # for data import and dissection import numpy as np # for data analysis import statsmodels.formula.api as smf import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: Load the relevant libraries End of explanation plt.interactive...