Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,400
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='step1'></a> 22 - Example Simulation Step1: <a id='step2'></a> Step2: 1. Create your module and evaluate irradiance without the mirror element Step3: 2. Add Mirror Approach 1 Step4:...
Python Code: import os from pathlib import Path testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_22') if not os.path.exists(testfolder): os.makedirs(testfolder) print ("Your simulation will be stored in %s" % testfolder) import bifacial_radiance import numpy as np ...
4,401
Given the following text description, write Python code to implement the functionality described below step by step Description: word2vec This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from Google. Training Download some data, for example Step1: Run word2phrase to gr...
Python Code: import word2vec Explanation: word2vec This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from Google. Training Download some data, for example: http://mattmahoney.net/dc/text8.zip End of explanation word2vec.word2phrase('/Users/drodriguez/Downloads/text8', '/U...
4,402
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...
4,403
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Pairs Trading By Delaney Mackenzie and Maxwell Margenot Part of the Quantopian Lecture Series Step1: Generating Two Fake Securities We model X's daily returns by drawing fro...
Python Code: import numpy as np import pandas as pd import statsmodels import statsmodels.api as sm from statsmodels.tsa.stattools import coint # just set the seed for the random number generator np.random.seed(107) import matplotlib.pyplot as plt Explanation: Introduction to Pairs Trading By Delaney Mackenzie and Maxw...
4,404
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploratory Analysis Round 2 Now that we have looked at the data on an unfiltered way, we now take into account information we know about the data. For example, the channels, channel types, ...
Python Code: # Import Necessary Libraries import numpy as np import os, csv, json from matplotlib import * from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import scipy from scipy.cluster.hierarchy import dendrogram, linkage from sklearn.neighbors import KernelDensity # pretty charting impor...
4,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Simplified Detection Efficiency Model Update to Step1: Station coordinates and thresholds from a set of log files Specify Step2: Station coordinates from csv file Input network title and c...
Python Code: %pylab inline import numpy as np import matplotlib.pyplot as plt import pandas as pd import parsed_functions as pf from mpl_toolkits.basemap import Basemap from coordinateSystems import TangentPlaneCartesianSystem, GeographicSystem, MapProjection c0 = 3.0e8 # m/s dt_rms = 23.e-9 # seconds sq = np.load('sou...
4,406
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id="top"></a> Db2 11 Time and Date Functions There are plenty of new date and time functions found in Db2 11. These functions allow you to extract portions from a date and format the date...
Python Code: %run db2.ipynb Explanation: <a id="top"></a> Db2 11 Time and Date Functions There are plenty of new date and time functions found in Db2 11. These functions allow you to extract portions from a date and format the date in a variety of different ways. While Db2 already has a number of date and time function...
4,407
Given the following text description, write Python code to implement the functionality described below step by step Description: String Methods In this lecture we are going to be looking at string methods in more detail. To simplify, a method is a function that are bound to a particular type of object. String methods,...
Python Code: print("hello".upper()) # This works print(str.upper()) # This returns an error, upper needs an argument Explanation: String Methods In this lecture we are going to be looking at string methods in more detail. To simplify, a method is a function that are bound to a particular type of object. String meth...
4,408
Given the following text description, write Python code to implement the functionality described below step by step Description: BC Grid Extrapolation Testing errors generated by grid extrapolation for extremely cool spot bolometric corrections. A first test of this will be to use a more extensive Phoenix color grid t...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import LinearNDInterpolator Explanation: BC Grid Extrapolation Testing errors generated by grid extrapolation for extremely cool spot bolometric corrections. A first test of this will be to use a more extensive Pho...
4,409
Given the following text description, write Python code to implement the functionality described below step by step Description: Classwork 3 Michael Seaman, Chinmai Raman, Austin Ayers, Taylor Patti Organized by Andrew Malfavon Excercise A.2 Step1: Chinmai Raman Classwork 3 5.49 Experience Overflow in a Function Calc...
Python Code: n = 30 plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fa),'g.') plt.show() plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fb) ** .5 ,'b.') plt.show() plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fc) ** .25 ,'y.') plt.show() plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fd),'r.') plt....
4,410
Given the following text description, write Python code to implement the functionality described below step by step Description: The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016...
Python Code: from six.moves import map, range, reduce Explanation: The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208...
4,411
Given the following text description, write Python code to implement the functionality described below step by step Description: Inspired by the work of Step1: 2. Project 5 data set import This cell Step2: 3. Print a dataset summary This cell Step3: 4. Exploratory visualization of the dataset This cell Step4: 5. G...
Python Code: # Visualisation parameters display_output = 1 train_verbose_style = 2 # 1 every training image, 2 once very epoch # Training parameters use_generator = 0 epoch_num = 30 train_model = 1 Explanation: Inspired by the work of: https://medium.com/@tuennermann/convolutional-neural-networks-to-find-cars-43cbc4fb...
4,412
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...
4,413
Given the following text description, write Python code to implement the functionality described below step by step Description: Andrea Manzini, Lorenzo Lazzara, Martin Josifoski, Mazen Fouad A-wali Mahdi 1. Introduction and General Information In this project, we analyze the LastFM dataset released in the framework o...
Python Code: %load_ext autoreload %autoreload 1 import numpy as np import pickle import matplotlib.pyplot as plt import scipy as sp import pandas as pd import os.path import networkx as nx from scipy.sparse import csr_matrix from Dataset import Dataset from plots import * import os from helpers import * %matplotlib inl...
4,414
Given the following text description, write Python code to implement the functionality described below step by step Description: The famous Monty Hall brain teaser Step2: setting up a game There are many ways to do this, but to keep it simple and human comprehensible I'm going to do it one game at a time. First up, ...
Python Code: import random import numpy as np # for plots, cause visuals %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: The famous Monty Hall brain teaser: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goat...
4,415
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate new columns with average block info Take average values over two time horizons 6 blocks (~1 min) -> represents the current state (short frequency view) 60 blocks (~10 min) -> repres...
Python Code: df['txcnt_second'] = df['tx_count'].values / df['blockTime'].values df['avg_gasUsed_t_perblock'] = df.groupby('block_id')['gasUsed_t'].transform('mean') df['avg_price_perblock'] = df.groupby('block_id')['price_gwei'].transform('mean') def rolling_avg(window_size): price = df[['block_id', 'avg_pric...
4,416
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step9: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be us...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson...
4,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Begin testing here Step1: As given by newport (https Step2: So we should expect about 0.25 maximum intensity through our 780 waveplate. tinkering below here
Python Code: qwp = np.matrix([[1, 0],[0, -1j]]) R(-np.pi/4)*qwp*R(np.pi/4) qwp45 = wp(np.pi/2, np.pi/4) qwp45 wp(np.pi/2, 0) vpol = np.matrix([[0,0],[0,1]]) vpol np.exp(1j*np.pi/4) horiz = np.matrix([[1],[0]]) output = qwp*horiz intensity(output) before_cell = wp(np.pi/2,np.pi/4)*wp(np.pi,np.pi/10)*horiz output = vpol*...
4,418
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l...
Python Code: import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) Explanation: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstra...
4,419
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Say I have these 2D arrays A and B.
Problem: import numpy as np A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) dims = np.maximum(B.max(0),A.max(0))+1 result = A[~np.in1d(np.ravel_multi_index(A.T,dims),np.ravel_multi_index(B.T,dims))] output = np.append(result, B[~np.in1d(np...
4,420
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.e - Correction de l'interrogation écrite du 26 septembre 2015 tests, boucles, fonctions Step1: Enoncé 1 Q1 Le programme suivant provoque une erreur pourquoi ? Step2: On découvre le prob...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.e - Correction de l'interrogation écrite du 26 septembre 2015 tests, boucles, fonctions End of explanation tab = [1, 3] for i in range(0, len(tab)): print(tab[i] + tab[i+1]) Explanation: Enoncé 1 Q1 Le programme suivant pro...
4,421
Given the following text description, write Python code to implement the functionality described below step by step Description: Manuscript3 - Analysis of Intrinsic Network FC Properties for Fig. 3 Master code for Ito et al., 2017¶ Takuya Ito (takuya.ito@rutgers.edu) Step1: 1.0 Basic parameters Step2: 2.0 Compute ou...
Python Code: import sys sys.path.append('utils/') import numpy as np import loadGlasser as lg import scipy.stats as stats from IPython.display import display, HTML import matplotlib.pyplot as plt import statsmodels.sandbox.stats.multicomp as mc import sys import multiprocessing as mp import pandas as pd import multregr...
4,422
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple example of local processing In this first tutorial we will show a complete example of usage of the library using some example datasets provided with it. Importing the library Importin...
Python Code: import gmql as gl Explanation: Simple example of local processing In this first tutorial we will show a complete example of usage of the library using some example datasets provided with it. Importing the library Importing the library End of explanation dataset1 = gl.get_example_dataset("Example_Dataset_1"...
4,423
Given the following text description, write Python code to implement the functionality described below step by step Description: A Hierarchical model for Rugby prediction Step2: This is a Rugby prediction exercise. So we'll input some data Step3: The model. <p>The league is made up by a total of T= 6 teams, playing ...
Python Code: !date import numpy as np import pandas as pd try: from StringIO import StringIO except ImportError: from io import StringIO %matplotlib inline import pymc3 as pm3, theano.tensor as tt Explanation: A Hierarchical model for Rugby prediction End of explanation data_csv = StringIO(home_team,away_team,h...
4,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Sun-Earth System NOTE Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Setting Parameters Step3: Running Comput...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Sun-Earth System NOTE: planets are currently under testing and not yet supported Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update ...
4,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
4,426
Given the following text description, write Python code to implement the functionality described below step by step Description: eDisGo basic example This example shows you the first steps with eDisGo. Grid expansion costs for an example distribution grid are calculated assuming renewable and conventional power plant ...
Python Code: import os import sys import pandas as pd from edisgo import EDisGo Explanation: eDisGo basic example This example shows you the first steps with eDisGo. Grid expansion costs for an example distribution grid are calculated assuming renewable and conventional power plant capacities as stated in the scenario ...
4,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Acceptance conditions The acceptance condition of an automaton specifies which of its paths are accepting. The way acceptance conditions are stored in Spot is derived from the way acceptance...
Python Code: spot.mark_t() spot.mark_t([0, 2, 3]) spot.mark_t((0, 2, 3)) Explanation: Acceptance conditions The acceptance condition of an automaton specifies which of its paths are accepting. The way acceptance conditions are stored in Spot is derived from the way acceptance conditions are specified in the HOA format....
4,428
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ml - Classification binaire avec features textuelles Ce notebook propose de voir comment incorporer des features pour voir l'amélioration des performances sur une classification binaire. ...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.ml - Classification binaire avec features textuelles Ce notebook propose de voir comment incorporer des features pour voir l'amélioration des performances sur une classification binaire. End of explanation from pyensae.datasour...
4,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC. Step1: <a href="https Step2: Explore checkpoints This section contains shows how to use the index.csv table for model selection. See vit_jax.checkpoint.get_augre...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # 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 r...
4,430
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 11. Going fast Step1: Question What is the typical size of particle system? Millenium run One of the most famous N-body computations is the Millenium run More than 10 billions parti...
Python Code: import numpy as np import math from numba import jit N = 10000 x = np.random.randn(N, 2); y = np.random.randn(N, 2); charges = np.ones(N) res = np.zeros(N) @jit def compute_nbody_direct(N, x, y, charges, res): for i in xrange(N): res[i] = 0.0 for j in xrange(N): dist = (x[i,...
4,431
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 3b Step1: Lab Task #1 Step2: Create two SQL statements to evaluate the model. Step3: Lab Task #2 Step4: Create three SQL statements to EVALUATE the model. Let's now retrieve the trai...
Python Code: %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_train LIMIT 0 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_eval LIMIT 0 Explanation: LAB 3b: BigQ...
4,432
Given the following text description, write Python code to implement the functionality described below step by step Description: Grove Light Sensor 1.1 This example shows how to use the Grove Light Sensor v1.1. You will also see how to plot a graph using matplotlib. The Grove Light Sensor produces an analog signal whi...
Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Grove Light Sensor 1.1 This example shows how to use the Grove Light Sensor v1.1. You will also see how to plot a graph using matplotlib. The Grove Light Sensor produces an analog signal which requires an ADC. The Grove ...
4,433
Given the following text description, write Python code to implement the functionality described below step by step Description: Target selection bits and bitmasks Author Step1: The mask contains the name of the target bit (e.g. ELG) the bit value to which that name corresponds (e.g. 1, meaning 2-to-the-power-1), a d...
Python Code: from desitarget.targets import desi_mask, bgs_mask, mws_mask print(desi_mask) Explanation: Target selection bits and bitmasks Author: Adam D. Myers, University of Wyoming This Notebook describes how to work with target selection bitmasks for DESI. Setting up your environment First, ensure that your environ...
4,434
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.x to 3.x Rule Migration Guide This guide describes changes needed for rules to run under Insights Core 3.x. It covers the following topics Step1: @rule Example Step2: <a id="filtering"><...
Python Code: # Boilerplate used in later cells # Not necessary for new rules. from pprint import pprint from insights.core import dr from insights.core.filters import add_filter, get_filters from insights.core.context import HostContext from insights.core.plugins import make_response, rule dr.load_components("insights....
4,435
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Automating image building We saw in the last notebook how we can build images of our funwave-tvd code and use Agave to make the process a bit easier. We can take some lessons learned ...
Python Code: writefile("funwave-tvd-docker-automation/Dockerfile", FROM stevenrbrandt/science-base MAINTAINER Steven R. Brandt <sbrandt@cct.lsu.edu> ARG BUILD_DATE ARG VERSION LABEL org.agaveplatform.ax.architecture="x86_64" \ org.agaveplatform.ax.build-date="\$BUILD_DATE" ...
4,436
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="width Step1: Import Python libraries Step2: Display options Step3: Set directories Step4: Chromedriver If you want to download from sources which require scraping, download t...
Python Code: version = '2020-10-06' changes = '''Yearly update''' Explanation: <div style="width:100%; background-color: #D9EDF7; border: 1px solid #CFCFCF; text-align: left; padding: 10px;"> <b>Time series: Processing Notebook</b> <ul> <li><a href="main.ipynb">Main Notebook</a></li> <li>Pro...
4,437
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started Step1: Creating the model First, we need to decide on the model type. For the given example, we are working with a continuous model. Step2: The model is based on the assump...
Python Code: import numpy as np from casadi import * # Add do_mpc to path. This is not necessary if it was installed via pip. import sys sys.path.append('../../') # Import do_mpc package: import do_mpc Explanation: Getting started: MHE Open an interactive online Jupyter Notebook with this content on Binder: In this Jup...
4,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: {TF Probability、R、Stan} における線形混合効果回帰 <table class="tfo-notebook-but...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
4,439
Given the following text description, write Python code to implement the functionality described below step by step Description: Préambule Step2: Exercice Robozzle
Python Code: if (cas simple): (solution immédiate) else: (solution récursive, impliquant un cas plus simple que le problème original) Explanation: Préambule : nous avons commencé par faire un rappel sur la récursivité en ré-écrivant le comportement de factorielle au tableau et en déroulant l'algorithme à l...
4,440
Given the following text description, write Python code to implement the functionality described below step by step Description: Record, Save, and Play Moves on a Poppy Creature This notebook is still work in progress! Feedbacks are welcomed! In this tutorial we will show how to Step1: Import the Move, Recorder and P...
Python Code: from pypot.creatures import PoppyErgo poppy = PoppyErgo() for m in poppy.motors: m.compliant = False m.goal_position = 0.0 Explanation: Record, Save, and Play Moves on a Poppy Creature This notebook is still work in progress! Feedbacks are welcomed! In this tutorial we will show how to: * record mo...
4,441
Given the following text description, write Python code to implement the functionality described below step by step Description: Exact solution used in MES runs We would like to MES the operation $$ J\nabla \cdot \mathbf{f}_\perp $$ Using cylindrical geometry. Step1: Initialize Step2: Define the variables Step3: De...
Python Code: %matplotlib notebook from sympy import init_printing from sympy import S from sympy import sin, cos, tanh, exp, pi, sqrt from boutdata.mms import x, y, z, t from boutdata.mms import Delp2, DDX, DDY, DDZ import os, sys # If we add to sys.path, then it must be an absolute path common_dir = os.path.abspath('....
4,442
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimisation Step1: As before, we can define an error function and minimise it Step2: We could also however define the inference problem statistically, by specifying a likelihood. Step3: ...
Python Code: import matplotlib.pyplot as plt import numpy as np import pints import pints.toy as toy # Create a model model = toy.LogisticModel() # Set some parameters real_parameters = [0.1, 50] # Create fake data times = model.suggested_times() values = model.simulate(real_parameters, times) sigma = 3 noisy_values = ...
4,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Energy Meter Examples BayLibre's ACME Cape and IIOCapture More information can be found at https Step1: Import required modules Step2: Target Configuration The target configuration is used...
Python Code: import logging from conf import LisaLogging LisaLogging.setup() Explanation: Energy Meter Examples BayLibre's ACME Cape and IIOCapture More information can be found at https://github.com/ARM-software/lisa/wiki/Energy-Meters-Requirements#iiocapture---baylibre-acme-cape. End of explanation # Generate plots i...
4,444
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is a simulation of 5000 ms of 400 independent descending commands following a gamma distribution with mean of 12 ms and order 10 and the Soleus muscle (800 motoneurons). Each d...
Python Code: import sys sys.path.insert(0, '..') import time import matplotlib.pyplot as plt %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'png') plt.rcParams['savefig.dpi'] = 75 plt.rcParams['figure.autolayout'] = False plt.rcParams['figure.figsize'] = 10, 6 plt....
4,445
Given the following text description, write Python code to implement the functionality described below step by step Description: Superradiance in the open Dicke model Step1: Wigner Function Below we calculate the Wigner function of the photonic part of the steady state. It shows two displaced squeezed states in the r...
Python Code: import matplotlib as mpl from matplotlib import cm import matplotlib.pyplot as plt import numpy as np from qutip import * from qutip.piqs import * #TLS parameters N = 6 ntls = N nds = num_dicke_states(ntls) [jx, jy, jz] = jspin(N) jp = jspin(N,"+") jm = jp.dag() w0 = 1 gE = 0.1 gD = 0.01 h = w0 * jz #photo...
4,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Collaborative filtering example collab models use data in a DataFrame of user, items, and ratings. Step1: That's all we need to create and train a model Step2: Movielens 100k Let's try wit...
Python Code: user,item,title = 'userId','movieId','title' path = untar_data(URLs.ML_SAMPLE) path ratings = pd.read_csv(path/'ratings.csv') ratings.head() Explanation: Collaborative filtering example collab models use data in a DataFrame of user, items, and ratings. End of explanation dls = CollabDataLoaders.from_df(rat...
4,447
Given the following text description, write Python code to implement the functionality described below step by step Description: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) Step3: 연습문제 12.1 이번 장에서 저자가 사용한 선형모형은 선형이라는 명백한 결점이 있고, 가격이 시간에 따라 선형으로 변할 것이라고 예측할 이유는 없다. 11.3 절에서...
Python Code: from __future__ import print_function import pandas import numpy as np import statsmodels.formula.api as smf import thinkplot import thinkstats2 import regression import timeseries %matplotlib inline Explanation: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) End o...
4,448
Given the following text description, write Python code to implement the functionality described below step by step Description: Elemento Truss El elemento Truss plano es un elemento finito con coordenadas locales y globales, tiene un modulo de elasticidad $E$, una sección transversal $A$ y una longitud $L$. Cada elem...
Python Code: %matplotlib inline from nusa import * # Importando nusa E,A = 210e9, 3.1416*(10e-3)**2 n1 = Node((0,0)) n2 = Node((2,0)) n3 = Node((0,2)) e1 = Truss((n1,n2),E,A) e2 = Truss((n1,n3),E,A) e3 = Truss((n2,n3),E,A) m = TrussModel() for n in (n1,n2,n3): m.add_node(n) for e in (e1,e2,e3): m.add_element(e) m.add_c...
4,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Análise Nodal com Fontes de Tensão Jupyter Notebook desenvolvido por Gustavo S.S. Um supernó é formado envolvendo-se uma fonte de tensão (dependente ou independente) conectada entre dois nós...
Python Code: print("Exemplo 3.3") import numpy as np from sympy import * Vsource = 2 Csource1 = 2 Csource2 = 7 R1 = 2 R2 = 4 R3 = 10 #i1 = v1/R1 = v1/2 #i2 = v2/R2 = v2/4 #i1 + i2 + 7 = 2 => i1 + i2 = -5 #v2 - v1 = 2 #v1/2 + v2/4 = -5 => (v2 - 2)/2 + v2/4 = - 5 #3v2/4 = -4 v2 = -16/3 v1 = v2 - 2 print("V1:", v1, "V") p...
4,450
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Image Classification Problem using Keras (dog_vs_cat) Step1: Data Preprocessing Step2: Define an architecture - > Feed Forward Network of dimension "3072-768-384-2"
Python Code: # import the necessary packages from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Activation from keras.optimizers import SGD from keras.layers import Dense from keras.utils import np_utils from i...
4,451
Given the following text description, write Python code to implement the functionality described below step by step Description: Mahalanobis Distance This notebook shows how I think we should do Mahalanobis distance for the SECIM project. From JMP Website Step1: Generation of a simulated data set As an example I will...
Python Code: import pandas as pd import numpy as np import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt import cPickle as pickle import os %matplotlib inline Explanation: Mahalanobis Distance This notebook shows how I think we should do Mahalanobis distance for the SECIM project. From JMP Web...
4,452
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute MNE inverse solution on evoked data in a mixed source space Create a mixed source space and compute MNE inverse solution on evoked dataset. Step1: Set up our source space. Step2: W...
Python Code: # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD (3-clause) import os.path as op import matplotlib.pyplot as plt from nilearn import plotting import mne from mne.minimum_norm import make_inverse_operator, apply_inverse # Set dir data_path = mne.datasets.sample.data_path() subject = ...
4,453
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"); Step1: How to use the GFSA layer for new tasks This notebook describes the high-level process for ...
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...
4,454
Given the following text description, write Python code to implement the functionality described below step by step Description: Model understanding and interpretability In this colab, we will - Will learn how to interpret model results and reason about the features - Visualize the model results Please complete the e...
Python Code: import time # We will use some np and pandas for dealing with input data. import numpy as np import pandas as pd # And of course, we need tensorflow. import tensorflow as tf from matplotlib import pyplot as plt from IPython.display import clear_output tf.__version__ Explanation: Model understanding and int...
4,455
Given the following text description, write Python code to implement the functionality described below step by step Description: Statistics There are many specialized packages for dealing with data analysis and statistical programming. One very important code that you will see in MATH1024, Introduction to Probability ...
Python Code: !head southampton_precip.txt Explanation: Statistics There are many specialized packages for dealing with data analysis and statistical programming. One very important code that you will see in MATH1024, Introduction to Probability and Statistics, is R. A Python package for performing similar analysis of l...
4,456
Given the following text description, write Python code to implement the functionality described below step by step Description: Statistics Fundamentals Statistics is primarily about analyzing data samples, and that starts with udnerstanding the distribution of data in a sample. Analyzing Data Distribution A great dea...
Python Code: import pandas as pd df = pd.DataFrame({'Name': ['Dan', 'Joann', 'Pedro', 'Rosie', 'Ethan', 'Vicky', 'Frederic'], 'Salary':[50000,54000,50000,189000,55000,40000,59000]}) print (df['Salary'].mean()) Explanation: Statistics Fundamentals Statistics is primarily about analyzing data samples, ...
4,457
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Tutorial Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that w...
Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict %matplotlib inline np.random.seed(1) Explanation: TensorFlow Tutorial Welcome to...
4,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: ¿Por qué PyCUDA? Hasta ahora hemos visto que si bien CUDA no es un lenguaje imposible de aprender, puede llegar a ser un dolor de cabeza el tener muchos apuntadores y manejar la memor...
Python Code: import pycuda.autoinit import pycuda.driver as drv import numpy from pycuda.compiler import SourceModule mod = SourceModule( __global__ void multiplicar(float *dest, float *a, float *b) { const int i = threadIdx.x; dest[i] = a[i] * b[i]; } ) multiplicar = mod.get_function("multiplicar") a = numpy.rando...
4,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 4 Step1: 2. Uso de Pandas para descargar datos de precios de cierre Ahora, en forma de función Step2: Una vez cargados los paquetes, es necesario definir los tickers de las acciones ...
Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np import datetime from datetime import datetime import scipy.stats as stats import scipy as sp import scipy.optimize as scopt import matplotlib.pyplot as plt import seaborn as sns %matplotlib ...
4,460
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute Now that we have datasets added to our Bundle, our next step is to run the forward model and compute a synthetic model for each of these datasets. Setup Let's first make sure we have...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: Compute Now that we have datasets added to our Bundle, our next step is to run the forward model and compute a synthetic model for each of these datasets. Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if ...
4,461
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility Space * Previous Step1: Import section specific modules Step2: 4.5.1 UV coverage Step3: Let's...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: <a id='beginning'></a> <!--\label{beginning}--> * Outline * Glossary * 4. The Visibility Space * Previous: 4.4 The Visibility Function ...
4,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting topographic maps of evoked data Load evoked data and plot topomaps for selected time points using multiple additional options. Step1: Basic Step2: If times is set to None at most...
Python Code: # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # Tal Linzen <linzen@nyu.edu> # Denis A. Engeman <denis.engemann@gmail.com> # Mikołaj Magnuski <mmagnuski@swps.edu.pl> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import numpy as np import ...
4,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Acoustic system calibration Since the calibration measurements may be dealing with very small values, there's potential for running into the limitations of <a href="https Step1: Calculating...
Python Code: %matplotlib inline from scipy import signal from scipy import integrate import pylab as pl import numpy as np Explanation: Acoustic system calibration Since the calibration measurements may be dealing with very small values, there's potential for running into the limitations of <a href="https://docs.oracle...
4,464
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Step1: Writing the objective function We can decompose the objective function as the sum of a least squares loss function and an $\ell_1$ regularizer. Step2: Generating da...
Python Code: import cvxpy as cp import numpy as np import matplotlib.pyplot as plt Explanation: Machine Learning: Lasso Regression Lasso regression is, like ridge regression, a shrinkage method. It differs from ridge regression in its choice of penalty: lasso imposes an $\ell_1$ penalty on the paramters $\beta$. That i...
4,465
Given the following text description, write Python code to implement the functionality described below step by step Description: Heap La structure heap ou tas en français est utilisée pour trier. Elle peut également servir à obtenir les k premiers éléments d'une liste. Step1: Un tas est peut être considéré comme un t...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Heap La structure heap ou tas en français est utilisée pour trier. Elle peut également servir à obtenir les k premiers éléments d'une liste. End of explanation %matplotlib inline Explanation: Un tas est peut être considéré comme u...
4,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Dans ce notebook je récupère une liste de chocs Tore Supra obtenue avec Ged. Pour chacun de ces chocs, je récupère les signaux de puissance FCI, et j'en déduis la puissance couplée max et l...
Python Code: from pywed import * # Tore Supra database library %pylab inline pulse_list = np.loadtxt('data/liste_choc_fci.txt', dtype=int) pulse_list = np.arange(44092, 48311, dtype='int') ts_max_power = [] ts_max_duration = [] for pulse in pulse_list: #print('Retrieve date for pulse {}'.format(pulse)) # retrie...
4,467
Given the following text description, write Python code to implement the functionality described below step by step Description: What is the true normal human body temperature? Background The mean normal body temperature was held to be 37$^{\circ}$C or 98.6$^{\circ}$F for more than 120 years since it was first concept...
Python Code: import pandas as pd %matplotlib inline df = pd.read_csv('data/human_body_temperature.csv') Explanation: What is the true normal human body temperature? Background The mean normal body temperature was held to be 37$^{\circ}$C or 98.6$^{\circ}$F for more than 120 years since it was first conceptualized and r...
4,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 4 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: If we want to do any "feature engi...
Python Code: import graphlab Explanation: Regression Week 4: Ridge Regression (gradient descent) In this notebook, you will implement ridge regression via gradient descent. You will: * Convert an SFrame into a Numpy array * Write a Numpy function to compute the derivative of the regression weights with respect to a sin...
4,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Random forest parameter-tuning Table of contents Data preprocessing Validation curves KS-test tuning Step1: Data preprocessing Load simulation dataframe and apply specified quality cuts Ext...
Python Code: import sys sys.path.append('/home/jbourbeau/cr-composition') print('Added to PYTHONPATH') from __future__ import division, print_function from collections import defaultdict import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn.ap...
4,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-label data stratification With the development of more complex multi-label transformation methods the community realizes how much the quality of classification depends on how the data ...
Python Code: from skmultilearn.dataset import load_dataset X,y, _, _ = load_dataset('scene', 'undivided') Explanation: Multi-label data stratification With the development of more complex multi-label transformation methods the community realizes how much the quality of classification depends on how the data is split in...
4,471
Given the following text description, write Python code to implement the functionality described below step by step Description: First Step Step1: Now, we have the data stored as a DataFrame titled "imdb". As a simple first step, we'd like to see the structure of this DataFrame. We'll use different ways to do this ("...
Python Code: imdb = pd.DataFrame.from_csv('imdb.csv', index_col=None) Explanation: First Step: Get the data from storage into the dataframe. Simple and easy method: pd.DataFrame.from_csv * CSV: Comma Separated Values, used in spreadsheets. Popular for import & export of smaller datasets. * Arguments: path-locat...
4,472
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: TPU 사용하기 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: TPU 초기화 TPU는 일반적으로 사용자 파이썬 프로그램을 실행하는 로...
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...
4,473
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 2 Imports Step1: Plotting with parameters Write a plot_sin1(a, b) function that plots $sin(ax+b)$ over the interval $[0,4\pi]$. Customize your visualization to make it eff...
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 2 Imports End of explanation t=np.linspace(0,4*np.pi,250) def plot_sine1(a, b): plt.figure(figsize=...
4,474
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculating Ground Motion Intensity Measures The SMTK contains two modules for the characterisation of ground motion Step1: Get Response Spectrum - Nigam & Jennings Step2: Plot Time Series...
Python Code: # Import modules %matplotlib inline import numpy as np # Numerical Python package import matplotlib.pyplot as plt # Python plotting package # Import import smtk.response_spectrum as rsp # Response Spectra tools import smtk.intensity_measures as ims # Intensity Measure Tools periods = np.array([0.01, 0.02,...
4,475
Given the following text description, write Python code to implement the functionality described below step by step Description: Alternative More Detailed Solution for Lab01 - Task C Step1: First try - Computing the probability using for loops The following was not clear in the instructions Step2: And it works prett...
Python Code: %matplotlib inline import numpy as np from numpy.random import rand, randn import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 # Data generation n, d, k = 100, 2, 2 np.random.seed(20) X = rand(n, d) means = [rand(d) * 0.5 + 0.5 , - rand(d) * 0.5 + 0.5] # for better plotting when k = 2 S = ...
4,476
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: From Landlab, we'll need a grid on which to plot data, and a plotting function. We'll start with just imshow_grid, but be aware that similar but more specifically named...
Python Code: import numpy as np Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a> Plotting grid data with Landlab <hr> <small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html">https://landlab.re...
4,477
Given the following text description, write Python code to implement the functionality described below step by step Description: MachineLearningWorkShop at UCSC Aug 18th - Learning with TESS Simulated data Last month we explored all type of learning algorithms with simulated light curves including Step1: Let's first ...
Python Code: import sklearn from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import train_test_split from sklearn.utils import shuffle from sklearn import metrics from sklearn.metrics import roc_curve from sklearn.metrics import classification_report from sklearn.decomposition import PC...
4,478
Given the following text description, write Python code to implement the functionality described below step by step Description: Process Discovery by Step1: Observe that the process model that we discovered, describes the same behavior as the model that we have shown above. As indicated, the algorithm used in this ex...
Python Code: import pandas as pd import pm4py df = pm4py.format_dataframe(pd.read_csv('data/running_example.csv', sep=';'), case_id='case_id',activity_key='activity', timestamp_key='timestamp') bpmn_model = pm4py.discover_bpmn_inductive(df) pm4py.view_bpmn(bpmn_model) Explanation: Process D...
4,479
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'awi', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: AWI Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, Thermodynamics,...
4,480
Given the following text description, write Python code to implement the functionality described below step by step Description: Data and Data Visualization Machine learning, and therefore a large part of AI, is based on statistical analysis of data. In this notebook, you'll examine some fundamental concepts related t...
Python Code: import statsmodels.api as sm df = sm.datasets.get_rdataset('GaltonFamilies', package='HistData').data df Explanation: Data and Data Visualization Machine learning, and therefore a large part of AI, is based on statistical analysis of data. In this notebook, you'll examine some fundamental concepts related ...
4,481
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Registration Settings Step1: Read the RIRE data and generate a larger point set as a reference Step2: Initial Alignment We use the CenteredTransformInitializer. Should w...
Python Code: import SimpleITK as sitk # Utility method that either downloads data from the network or # if already downloaded returns the file name for reading from disk (cached data). from downloaddata import fetch_data as fdata # Always write output to a separate directory, we don't want to pollute the source directo...
4,482
Given the following text description, write Python code to implement the functionality described below step by step Description: Widgets in a Jupyter Notebook An example of using version 4.x widgets in a Jupyter Notebook. Reference Step1: Define a sine wave Step2: Plot the sine wave Step3: Define a function that al...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact Explanation: Widgets in a Jupyter Notebook An example of using version 4.x widgets in a Jupyter Notebook. Reference: https://ipywidgets.readthedocs.io/en/latest/. Depending on the current state of your Pyt...
4,483
Given the following text description, write Python code to implement the functionality described below step by step Description: The purpose of this notebook is twofold. First, it demonstrates the basic functionality of PyLogit for estimating nested logit models. Secondly, it compares the nested logit capabilities of ...
Python Code: from collections import OrderedDict # For recording the model specification import pandas as pd # For file input/output import numpy as np # For vectorized math operations import statsmodels.tools.numdiff as numdiff # For numeric hessian import scipy.linalg ...
4,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
4,485
Given the following text description, write Python code to implement the functionality described below step by step Description: Radiation Forces on Circumplanetary Dust This example shows how to integrate circumplanetary dust particles under the action of radiation forces. We use Saturn's Phoebe ring as an example, ...
Python Code: import rebound import reboundx import numpy as np sim = rebound.Simulation() sim.G = 6.674e-11 # SI units sim.dt = 1.e4 # Initial timestep in sec. sim.N_active = 2 # Make it so dust particles don't interact with one another gravitationally sim.add(m=1.99e30, hash="Sun") # add Sun with mass in kg sim.add(m=...
4,486
Given the following text description, write Python code to implement the functionality described below step by step Description: Stacks Getting Started Welcome to the Subinitial Stacks Getting Started Guide! This document will guide you through setup of the Stacks and your first script. Useful Links Official Hardware ...
Python Code: !pip3 install --user git+https://bitbucket.org/subinitial/subinitial.git Explanation: Stacks Getting Started Welcome to the Subinitial Stacks Getting Started Guide! This document will guide you through setup of the Stacks and your first script. Useful Links Official Hardware Getting Started Guide Official ...
4,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction GPU Chainer とはニューラルネットの実装を簡単にしたフレームワークです。 今回は言語の分野でニューラルネットを適用してみました。 今回は言語モデルを作成していただきます。 言語モデルとはある単語が来たときに次の単語に何が来やすいかを予測するものです。 言語モデルにはいくつか種類があるのでここでも紹介しておきます。 n-グラム言語モデル 単語の...
Python Code: import time import math import sys import pickle import copy import os import re import numpy as np from chainer import cuda, Variable, FunctionSet, optimizers import chainer.functions as F Explanation: Introduction GPU Chainer とはニューラルネットの実装を簡単にしたフレームワークです。 今回は言語の分野でニューラルネットを適用してみました。 今回は言語モデルを作成していただきます。 ...
4,488
Given the following text description, write Python code to implement the functionality described below step by step Description: GPFlow first approximation Step1: Simulating Data Simulate random uniform 4-d vector. Give N of this. Step2: Calculate distance X can be interpreted as covariate matrix in which the first ...
Python Code: ## Import modules import numpy as np import scipy.spatial.distance as sp from matplotlib import pyplot as plt plt.style.use('ggplot') ## Parameter definitions N = 1000 phi = 0.05 sigma2 = 1.0 beta_0 = 10.0 beta_1 = 1.5 beta_2 = -1.0 # AL NAGAT nugget = 0.03 Explanation: GPFlow first approximation End of ex...
4,489
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cas', 'sandbox-1', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: CAS Source ID: SANDBOX-1 Topic: Ocnbgchem Sub-Topics: Tracers. Proper...
4,490
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Running a Tapas fine-tuned checkpoint This notebook shows how to load and make predictions with TAPAS model, which was introduced in the paper Step2: Fetch models fom...
Python Code: # Copyright 2019 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
4,491
Given the following text description, write Python code to implement the functionality described below step by step Description: From here is seems clear that the criteria necessary to satisfy the "suspect" condition are relatively narrow, and the real issue is whether or not poor photometry significantly affects the ...
Python Code: print("Of the {} mean det sources, {} have suspect, and {} have poor photometry".format(sum(mean_det), sum(mean_det & suspect_phot), sum(mean_det & poor_phot))) Explanation: From here is seems clear that the criteria necessary to satisfy the "suspect" condition are relatively narrow, and the real issue is ...
4,492
Given the following text description, write Python code to implement the functionality described below step by step Description: Molecular Dynamics Step1: Basics of Molecular Dynamics
Python Code: from IPython.core.display import HTML css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css' HTML(url=css_file) Explanation: Molecular Dynamics: Lab 1 In part based on Fortran code from Furio Ercolessi. End of explanation %matplotlib inline import n...
4,493
Given the following text description, write Python code to implement the functionality described below step by step Description: 7 - Advanced topics - Multiple SceneObjects Example This journal shows how to Step1: <a id='step1a'></a> A. Generating the first scene object This is a standard fixed-tilt setup for one hou...
Python Code: import os import numpy as np import pandas as pd from pathlib import Path testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_07') if not os.path.exists(testfolder): os.makedirs(testfolder) print ("Your simulation will be stored in %s" % testfolder) from...
4,494
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimisation in a transformed parameter space This example shows you how to run an optimisation in a transformed parameter space, using a pints.Transformation object. Parameter transformatio...
Python Code: import matplotlib.pyplot as plt import numpy as np import pints import pints.toy as toy # Set some random seed so this notebook can be reproduced np.random.seed(10) # Load a logistic forward model model = toy.LogisticModel() Explanation: Optimisation in a transformed parameter space This example shows you ...
4,495
Given the following text description, write Python code to implement the functionality described below step by step Description: Teorema da Convolução Convolução periódica Antes de falarmos sobre o Teorema da Convolução, precisamos entender a convolução periódica (pconv). Até agora, vimos a convolução linear (conv ou ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from numpy.fft import * import sys,os ia898path = os.path.abspath('../../') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia f = np.array([[1,0,0,0,0,0,0,0,0], ...
4,496
Given the following text description, write Python code to implement the functionality described below step by step Description: Contact Binary with Spots Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't w...
Python Code: !pip install -I "phoebe>=2.2,<2.3" %matplotlib inline Explanation: Contact Binary with Spots Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of expla...
4,497
Given the following text description, write Python code to implement the functionality described below step by step Description: Updating Plots bqplot is an interactive plotting library. Attributes of plots can be updated in place without recreating the whole figure and marks. Let's look at idiomatic ways of updating ...
Python Code: import numpy as np import bqplot.pyplot as plt x = np.linspace(-10, 10, 100) y = np.sin(x) fig = plt.figure() line = plt.plot(x=x, y=y) fig Explanation: Updating Plots bqplot is an interactive plotting library. Attributes of plots can be updated in place without recreating the whole figure and marks. Let's...
4,498
Given the following text description, write Python code to implement the functionality described below step by step Description: Java vs Python Who am I? Cesare Placanica Cisco Photonics NMTG group. Java developer since 2010 (Java 1.5/1.7, Spring, Hibernate and Tomcat). Previously C/C++ embedded RTOSes. Python Wannabe...
Python Code: "Elapsed decorator." import datetime def elapsed(func): "Elapsed decorator" def _wrapper(*args, **kwargs): "Decoration function" start = datetime.datetime.now() ret = func(*args, **kwargs) print("Elapsed time", datetime.datetime.now() - start) return ret ...
4,499
Given the following text description, write Python code to implement the functionality described below step by step Description: What's New in Marvin 2.2! Lots of things are new in Marvin 2.2.0. See the list with links to individual sections here http Step1: Smarter handling of inputs You can still specify plateifu,...
Python Code: %matplotlib inline from marvin import config config.switchSasUrl('local') config.forceDbOff() from marvin.tools.cube import Cube plateifu='8485-1901' cube = Cube(plateifu=plateifu) print(cube) maps = cube.getMaps(bintype='HYB10') print(maps) Explanation: What's New in Marvin 2.2! Lots of things are new in ...