Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
2,200
<ASSISTANT_TASK:> Python Code: import sys def maxSubArraySum(a , n , k , i ) : max_so_far = - sys . maxsize ; max_ending_here = 0 ; while(i < n ) : max_ending_here = max_ending_here + a[i ] ; if(max_so_far < max_ending_here ) : max_so_far = max_ending_here ;  if(max_ending_here < 0 ) : max_ending...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
2,201
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.spatial import matplotlib.pyplot as plt %matplotlib inline d = 2 # Dimensionality. n = 100 # Number of samples. c = 1 # Number of communities. # Data matrix, structured in communities. X = np.random.uniform(0, 1, (n, d)) X += np.linspace(0, 2, c).re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1 Graph Step2: Step 2 Step3: Step 3 Step4: Step 4 Step5: Step 5 Step6: Step 6 Step7: 2 Fourier Basis Step8: Visualize the eigenvectors $u...
2,202
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'sandbox-2', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("nam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
2,203
<ASSISTANT_TASK:> Python Code: # For using the same code in either Python 2 or 3 from __future__ import print_function ## Note: Python 2 users, use raw_input() to get player input. Python 3 users, use input() from IPython.display import clear_output def display_board(board): pass def player_input(): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 1 Step2: Step 2 Step3: Step 3 Step4: Step 4 Step5: Step 5 Step6: Step 6 Step7: Step 7 Step8: Step 8 Step9: Step 9 Step10: Step 10
2,204
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn; seaborn.set() from clusterlensing import ClusterEnsemble import emcee import corner % matplotlib inline import matplotlib matplotlib.rcParams["axes.labelsize"] = 20 matplotlib.rcParams["legend.fontsize"] = 12 logm_true = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate a noisy measurement to fit Step2: Write down likelihood, prior, and posterior probilities Step3: Sample the posterior using emcee Ste...
2,205
<ASSISTANT_TASK:> Python Code: import requests as rq import pandas as pd import matplotlib.pyplot as mpl import bs4 import os from tqdm import tqdm_notebook from datetime import time %matplotlib inline base_url = "https://pydata.org" r = rq.get(base_url + "/berlin2018/schedule/") bs = bs4.BeautifulSoup(r.text, "html.p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Query Data Step2: Let's query every talk description Step3: Okay, make a dataframe and add some helpful columns Step4: visualize some stuff
2,206
<ASSISTANT_TASK:> Python Code: bounding_box_file = "" result_shapefile_filepath = "" p1 = pyproj.Proj("+init=epsg:31254") p2 = pyproj.Proj("+init=epsg:4326") p3 = pyproj.Proj("+init=epsg:3857") p4 = pyproj.Proj("+init=epsg:25832") import overpy import fiona import numpy import geopandas from shapely.ops import polygon...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import statements Step2: Utility functions Step3: Query OpenStreetMap using OverpassAPI via overpy python package Step4: define bounding box ...
2,207
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import pandas as pd from sklearn.cluster import KMeans from sklearn.preprocessing import minmax_scale def load_data(file_path, cols=None): COL_NAMES = ["duration", "protocol_type", "service", "flag", "src_bytes", "dst_bytes", "land", "wrong_fragme...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Loading Step2: K-Means Evaluation Step3: Loading the training data Step4: Training Step5: Test Set Step6: Now to cluster the test data...
2,208
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt #Load libraries for data processing import pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv) import numpy as np from scipy.stats import norm # visualization import seaborn as sns plt.style.use('fivethirtyeight') sns.set_styl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Label encoding Step2: After encoding the class labels(diagnosis) in an array y, the malignant tumors are now represented as class 1(i.e prescen...
2,209
<ASSISTANT_TASK:> Python Code: import os.path as op import numpy as np import mne data_path = mne.datasets.opm.data_path() subject = 'OPM_sample' subjects_dir = op.join(data_path, 'subjects') raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif') bem_fname = op.join(subjects_dir, subject, 'bem', ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Prepare data for localization Step2: Examine our coordinate alignment for source localization and compute a Step3: Perform dipole fitting Step...
2,210
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d import torch from torch.utils.data import Dataset, DataLoader import torch.nn as nn class plot_error_surfaces(object): def __init__(self,w_range, b_range,X,Y,n_samples=50,go=True): W = np.lin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Helper functions Step2: <a id="ref0"></a> Step3: <a id="ref1"></a> Step4: Create a logistic regression object or model Step5: Replace the r...
2,211
<ASSISTANT_TASK:> Python Code: import json import os import nltk import string import re import pandas as pd from IPython.display import display import numpy as np import math directory = 'sitespider/sites' files = [x[2] for x in os.walk(directory)][0] pages = [] for file in files: with open("%s/%s" % (directory,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: a) Implement a crawler Step2: Importierung der analysierten Seiten Step3: Konstanten Step4: Funktionen Step5: Hilfe-Funktionen Step6: Die F...
2,212
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import os print os.getenv("HOME") wd = os.path.join( os.getenv("HOME"),"mpi_tmpdir") if not os.path.isdir(wd): os.mkdir(wd) os.chdir(wd) print "WD is now:",os.getcwd() %%writefile mpi002.py from mpi4py import MPI i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: non-contigous slice Step2: N - slices
2,213
<ASSISTANT_TASK:> Python Code: from napalm import get_network_driver import napalm_yang import json def use_mock_devices(): junos_configuration = { 'hostname': '127.0.0.1', 'username': 'vagrant', 'password': '', 'optional_args': {'path': "./junos_mock/", 'profile': ['junos'], ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating a Binding Step2: At this point, you can use the "util" model_to_dict() to visualize the binding and the attached models Step3: Popula...
2,214
<ASSISTANT_TASK:> Python Code: import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample, fetch_hcp_mmp_parcellation from mne.minimum_norm import apply_inverse, read_inverse_operator from mne import read_evokeds data_path = sample.data_path() sample_dir = op.join...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then, we read the stc from file. Step2: This is a Step3: The SourceEstimate object is in fact a surface source estimate. MNE also Step4: You...
2,215
<ASSISTANT_TASK:> 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 ! pip3 install -U google-cloud-storage $USER_FLAG if not os.getenv("IS_TESTING...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Before you begin Step4: Region Step5:...
2,216
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'thu', 'ciesm', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "email") ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
2,217
<ASSISTANT_TASK:> Python Code: # useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit.tools.visualization import plot_histogram from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance from qiski...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: [Optional] Setup token to run the experiment on a real device Step2: MaxCut problem Step3: Brute force approach Step4: Mapping to the Ising p...
2,218
<ASSISTANT_TASK:> Python Code: %run '00_database_connectivity_setup.ipynb' IPython.display.clear_output() %%execsql drop table if exists gp_ds_sample_table; create temp table gp_ds_sample_table as ( select random() as x, random() as y from generate_series(1, 10) x ) distributed rand...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Your connection object is conn Step4: SELECT query
2,219
<ASSISTANT_TASK:> Python Code: 3 * 4 x = [1, 2, 3] print(x) x.append(4) print(x) measurements = {'height': [1.70, 1.80, 1.50], 'weight': [60, 120, 50]} measurements measurements['height'] x = [1, 2, 3, 4] [i**2 for i in x] def calc_bmi(weight, height): return weight / height**2 [calc_bmi(w, h) for w, h in zip(me...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lists Step2: Dictionaries Step3: Comprehensions Step4: Level 1 Step5: Mixed types Step6: Grouping Step7: Seaborn Step8: 2D distributions ...
2,220
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np tmp = np.array([1., 2., 3.]) tmp_cubed = tmp**3 print(tmp) print(tmp_cubed) ex_dataframe = pd.DataFrame() ex_dataframe['power_1'] = tmp print(ex_dataframe) def polynomial_sframe(feature, degree): # assume that degree >= 1 # initialize the ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArr...
2,221
<ASSISTANT_TASK:> Python Code: rdt_dict = { 50: [184, 184, 184, 184, 279, 184, 198, 279, 192, 326], 100: [345, 501, 350, 350, 492, 350, 350, 496, 495, 350], 150: [501, 648, 648, 648, 501, 648, 648, 648, 501, 567], 200: [800, 800, 800, 800, 690, 800, 800, 800, 660, 800], 250: [960, 960, 960, 960, 96...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Raspberry Pi using USB2Dynamixel Step2: Plots Step3: Baud rate
2,222
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plot from ipywidgets import interactive import ipywidgets as widgets import math from pulp import * %matplotlib inline # returns rho polynomial (highest exponents first) corresponding to average check node degree c_avg def c_avg_to_rho(c_a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We specify the check node degree distribution polynomial $\rho(Z)$ by fixing the average check node degree $d_{\mathtt{c},\text{avg}}$ and assum...
2,223
<ASSISTANT_TASK:> Python Code: import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.optimizers import SGD, Adadelta from keras.callbacks import RemoteMonitor import sys sys.path.append('../python') from data import Corpus with Corpus('../data/mfcc_train_smal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First let's load our data. In the VoxforgeDataPrep notebook, we created to arrays - inputs and outputs. The input nas the dimensions (num_sample...
2,224
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cccma', 'sandbox-3', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
2,225
<ASSISTANT_TASK:> Python Code: #!/usr/bin/python #-*- encoding: utf-8 -*- Sample Codes for ThinkStats2 - Chapter3 Copyright 2015 @myuuuuun URL: https://github.com/myuuuuun/ThinkStats2-Notebook License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html %matplotlib inline from __future__ import division, print_function impo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ThinkStat2 Chapter2 Exerciseのサンプルコード 実行例 Step2: Exercise1 Step3: Exercise2 Step4: thinkstats2モジュールに入っているメソッド値が一致しているか調べる Step5: Exercise3 ...
2,226
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt # Regresa 101 numeros igualmmente espaciados en el intervalo[-1,1] x_train = np.linspace(-1, 1, 101) # Genera numeros pseudo-aleatorios multiplicando la matriz x_train * 2 y # sumando a cada elemento un ruido (una matriz del mismo tamani...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Algoritmo de Regresion Lineal en TensorFlow Step2: Regresion Lineal en Polinomios de grado N Step3: Regularizacion
2,227
<ASSISTANT_TASK:> Python Code: max_steps = 3000 batch_size = 128 data_dir = 'data/cifar10/cifar-10-batches-bin/' model_dir = 'model/_cifar10_v2/' X_train, y_train = cifar10_input.distorted_inputs(data_dir, batch_size) X_test, y_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size) image...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 初始化权重 Step2: 第一个卷积层 Step3: 第二个卷积层 Step4: 第一个全连接层 Step5: 第二个全连接层 Step6: 输出层 Step7: 使用in_top_k来输出top k的准确率,默认使用top 1。常用的可以是top 5。 Step8: 启动...
2,228
<ASSISTANT_TASK:> Python Code: import re, json, os, nltk, string, gensim, bz2 from gensim import corpora, models, similarities, utils from nltk.corpus import stopwords from os import listdir from datetime import datetime as dt import numpy as np import codecs import sys stdin, stdout, stderr = sys.stdin, sys.stdout, sy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Build LSI Model Step2: LsiModel的參數 Step3: Build Word2Vec Model Step4: Build Doc2Vec Model Step5: Build Doc2Vec Model from 2013 USPTO Patents...
2,229
<ASSISTANT_TASK:> Python Code: %%capture --no-stderr !pip3 install kfp --upgrade import kfp.components as comp dataproc_submit_pig_job_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/1.7.0-rc.3/components/gcp/dataproc/submit_pig_job/component.yaml') help(dataproc_submit_pig...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the component using KFP SDK Step2: Sample Step3: Example pipeline that uses the component Step4: Compile the pipeline Step5: Submit the...
2,230
<ASSISTANT_TASK:> 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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 기본 분류 Step2: 패션 MNIST 데이터셋 임포트하기 Step3: load_data() 함수를 호출하면 네 개의 넘파이(NumPy) 배열이 반환됩니다 Step4: 데이터 탐색 Step5: 비슷하게 훈련 세트에는 60,000개의 레이블이 있습니다 ...
2,231
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import sys sys.path.append(os.path.join('..', '..')) from data_models.parameters import arl_path results_dir = arl_path('test_results') from matplotlib import pylab import numpy from astropy.coordinates import SkyCoord from astropy import units as u from astro...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Construct LOW core configuration Step2: We create the visibility. This just makes the uvw, time, antenna1, antenna2, weight columns in a table ...
2,232
<ASSISTANT_TASK:> Python Code: import rebound import reboundx import numpy as np sim = rebound.Simulation() rebound.G = 6.674e-11 # SI units sim.integrator = "whfast" sim.dt = 1.e8 # At ~100 AU, orbital periods ~1000 yrs, so use a timestep of 1% of that, in sec. sim.N_active = 1 # Make it so dust particles don't intera...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now let's set up REBOUNDx and add radiation_forces. We also have to set the speed of light in the units we want to use. Step2: By default, the...
2,233
<ASSISTANT_TASK:> Python Code: from IPython.display import display from IPython.display import ( HTML, Image, Latex, Math, Markdown, SVG ) text = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam urna libero, dictum a egestas non, placerat vel neque. In imperdiet iaculis fermentum. Vestibulum ante i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Text Step3: Text as output Step4: Standard error Step5: HTML Step7: Markdown Step9: LaTeX Step11: SVG
2,234
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) data_path = samp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters Step2: Compute covariance using automated regularization Step3: Show the evoked data Step4: We can then show whitening for our...
2,235
<ASSISTANT_TASK:> Python Code: import numpy as np from numpy.testing import assert_almost_equal # Specify diffusion coefficient nu = 0.1 def analytical_soln(xmax=1.0, tmax=0.2, nx=1000, nt=1000): Compute analytical solution. x = np.linspace(0, xmax, num=nx) t = np.linspace(0, tmax, num=nt) u = np.zeros(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Automatically 'discovering' the heat equation with reverse finite differencing Step3: Okay, so now that we have our data to work on, we need to...
2,236
<ASSISTANT_TASK:> Python Code: from cartoframes.auth import set_default_credentials set_default_credentials('cartoframes') from cartoframes.viz import Map, Layer, Layout, basic_style Layout([ Map(Layer('select * from drought_wk_1 where dm = 3', basic_style(color='#e15383'))), Map(Layer('select * from drought_w...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Same viewport Step2: Different viewports
2,237
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from scipy.stats import ttest_ind import numpy as np import mne from mne.channels import find_layout, find_ch_connectivity from mne.stats import spatio_temporal_cluster_test np.random.seed(0) # Load the data path = mne.datasets.kiloword.data_path() + '/kwor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If we have a specific point in space and time we wish to test, it can be Step2: Absent specific hypotheses, we can also conduct an exploratory ...
2,238
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Barachant <alexandre.barachant@gmail.com> # # License: BSD (3-clause) from mne import (io, compute_raw_covariance, read_events, pick_types, Epochs) from mne.datasets import sample from mne.preprocessing import Xdawn from mne.viz import plot_epochs_image print(__doc__)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters and read data
2,239
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Joan Massich <mailsik@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import os.path as op import numpy as np import mne from mne.datasets import eegbci from mne.datasets import fe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the data Step2: Setup source space and compute forward Step3: From here on, standard inverse imaging methods can be used! Step4: Get an ...
2,240
<ASSISTANT_TASK:> Python Code: from skmultilearn.dataset import load_dataset X_train, y_train, feature_names, label_names = load_dataset('emotions', 'train') X_test, y_test, _, _ = load_dataset('emotions', 'test') feature_names[:10] label_names from skmultilearn.problem_transform import BinaryRelevance from sklearn....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's load up some data. In this tutorial we will be working with the emotions data set introduced in emotions. Step2: The feature_names variab...
2,241
<ASSISTANT_TASK:> Python Code: from pathlib import Path import pathlib save_dir = "./test_dir" Path(save_dir).mkdir(parents=True, exist_ok=True) ### get current directory print(Path.cwd()) print(Path.home()) print(pathlib.Path.home().joinpath('python', 'scripts', 'test.py')) # Reading and Writing Files path = pathlib....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: useful functions Step2: .name Step3: Find the Last Modified File Step4: Create a Unique File Name Step5: dir exist and then glob with multip...
2,242
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from scipy import stats np.random.seed(0) mu = 0 sigma = 1 N = 3 np.random.lognormal(mean=mu, sigma=sigma, size=N) np.random.seed(0) stats.lognorm(sigma, loc=0, scale=np.exp(mu)).rvs(size=N) import paramnormal np.random.seed(0) paramnormal.lognorma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Consider the lognormal distribution. Step2: In scipy, you need an additional shape parameter (s), plus the usual loc and scale. Aside from the...
2,243
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from math import pi import control as ct def vehicle_update(t, x, u, params={}): Vehicle dynamics for cruise control system. Parameters ---------- x : array System state: car velocity in m/s u : array ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Process Model Step3: Engine model Step4: Torque curves for a typical car engine. The graph on the left shows the torque generated by the engin...
2,244
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] view_sentence_range = (0, 10) DON'T MODIFY ANYTHING IN THIS CELL import num...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
2,245
<ASSISTANT_TASK:> Python Code: from typing import Callable, Iterator, Tuple import chex import jax import jax.numpy as jnp import matplotlib.pyplot as plt import numpy as np import optax def generator() -> Iterator[Tuple[chex.Array, chex.Array]]: rng = jax.random.PRNGKey(0) while True: rng, k1, k2 = jax.random....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We demonstrate sampling from this as follows, Step2: We now define our parametrized function $f(\theta, x)$, and choose a random initial value ...
2,246
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os import glob import SimpleITK as sitk from PIL import Image from scipy.misc import imread %matplotlib inline from IPython.display import clear_output pd.options.mode.chained_assignment =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let us import annotations Step2: Candidates have two classes, one with nodules, one without Step3: Classes are heaviliy unbalanced, hardly 0.2...
2,247
<ASSISTANT_TASK:> Python Code: import pandas as pd import pandas.io.data as web import datetime # date ranges end = datetime.date(2015, 1, 26) start = end + datetime.timedelta(weeks=-21) start # Get daily price data for Caltex ctx = web.DataReader('ctx.ax', 'yahoo', start, end) ctx # resample to weekly ohlc data star...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get Daily price data for Caltex. Step2: Transform to Weekly Step3: All Ords Moving Average
2,248
<ASSISTANT_TASK:> Python Code: import numpy as np from IPython.display import SVG from keras.utils.vis_utils import model_to_dot import keras from keras.datasets import mnist # load up the training data! from keras.models import Sequential # our model from keras.layers import Dense, Dropout, Flatten # layers we've see...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We're going to use some examples from https Step2: Typically it's good practice to specify your parameters together Step3: In this case we alr...
2,249
<ASSISTANT_TASK:> Python Code: import os import matplotlib.pyplot as plt import pyzdde.zdde as pyz %matplotlib inline l = pyz.createLink() # create a DDE link object for communication zfile = os.path.join(l.zGetPath()[1], 'Sequential', 'Objectives', 'Cooke 40 degree field.zmx') l.zLoadFile(zfile) l.zQuickFocus() l.i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load a lens file Step2: Perform a quick-focus Step3: Example of a Layout plot Step4: Why do we need to set gamma? Step5: Now that we have t...
2,250
<ASSISTANT_TASK:> Python Code: import pandas as pd cancer = pd.read_csv('../data/cancer.csv') cancer ytotal, ntotal = cancer.sum().astype(float) p_hat = ytotal/ntotal p_hat p_hat*(1.-p_hat)*ntotal cancer.y.var() %matplotlib inline import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 2, figs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If we use a simple binomial model, which assumes independent samples from a binomial distribution with probability of mortality $p$, we can use ...
2,251
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy, matplotlib.pyplot as plt import seaborn as sns %matplotlib inline customers = pd.read_csv('Ecommerce Customers') customers.head() customers.describe() customers.info() sns.jointplot(customers['Time on Website'], customers['Yearly Amount Spent']) sns.j...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the Data Step2: Check the head of customers, and check out its info() and describe() methods. Step3: Exploratory Data Analysis Step4: Do ...
2,252
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-2', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
2,253
<ASSISTANT_TASK:> 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/A...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In this case study we'll develop a model of Spider-Man swinging from a springy cable of webbing attached to the top of the Empire State Building...
2,254
<ASSISTANT_TASK:> Python Code: import numpy as np file = "knapsack1.txt" fp = open(file, 'r+') data = fp.readlines() W, n = data[0].split(" ") W, n = int(W), int(n) v = [] w = [] for r in data[1:]: v_i, w_i = r.split(" ") v.append(int(v_i)) w.append(int(w_i)) A = np.zeros([n, W+1]) for i in range(n): fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problem 2 Step2: A recursive Implementation of the knapsack algorithm with caching
2,255
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import griddata m, n = 10, 4 xl, xr = (0.0, 1.0) yb, yt = (0.0, 1.0) h = (xr - xl) / (m - 1.0) k = (yt - yb) / (n - 1.0) xx = [xl + (i - 1)*h for i in range(1, m+1)] yy = [yb + (i - 1)*k for i in ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Para simplificar el sistema a resolver, cambiaremos los índices dobles por indices lineales mediante la conversión Step2: Luego debemos constru...
2,256
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/openai/baselines >/dev/null !pip install gym >/dev/null import numpy as np import random import gym from gym.utils import seeding from gym import spaces def state_name_to_int(state): state_name_map = { 'S': 0, 'A': 1, 'B': 2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Environment Step3: Try out Environment Step4: Baseline Step5: Train model Step7: Step 1 Step8: Step 2 Step9: Visualizing Results Step10: ...
2,257
<ASSISTANT_TASK:> Python Code: !pip show systemml import pandas as pd from systemml import MLContext, dml ml = MLContext(sc) print(ml.info()) sc.version FsPath = "/tmp/data/" inp = FsPath + "Input/" outp = FsPath + "Output/" import numpy as np X_pd = pd.DataFrame(np.arange(1,2001, dtype=np.float)).values.reshape(100...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: SystemML Read/Write data from local file system Step3: Generate Data and write out to file. Step4: Alternatively to passing in/out file names,...
2,258
<ASSISTANT_TASK:> Python Code: from itertools import islice def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b n = 45 known_good_output = tuple(islice(fibonacci(), n)) # known_good_output %timeit sum(islice(fibonacci(), n)) def fibonacci(): a, b = 0, 1 while True: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First we start with straightforward fibonacci generator function. Step2: Next, we unroll the loop. Note that there are no assignments that just...
2,259
<ASSISTANT_TASK:> Python Code: # Can't find good material for this... # Can't find good material for this. # Let us see what this would look like in numpy. # First make choose m and n such that m != n m = 5 n = 10 # Make the matrix A A = np.random.rand(m, n) print(A) # Now compute its eigenvalues. try: vals, vecs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: PCA Step2: PCA Algorithm Basics Step3: Looks like we'll have to cheat a bit. Step4: This.... actually makes sense. Lets compare the other mu...
2,260
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from ipywidgets import interact, FloatSlider import SimpleITK as sitk # Download data to work on %run update_path_to_download_script from downloaddata import fetch_data as fdata from myshow import myshow, myshow3d img_T1 = sitk.ReadImage(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Thresholding Step2: ITK has a number of histogram based automatic thresholding filters including Huang, MaximumEntropy, Triangle, and the popul...
2,261
<ASSISTANT_TASK:> Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) # Import Libraries %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Here, I introduce a ne...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Triangular mesh generation Step2: This quad mesh is already able to accurately describe the free-surface topography. Step3: Next, we compute ...
2,262
<ASSISTANT_TASK:> Python Code: %matplotlib inline import bigbang.mailman as mailman import bigbang.graph as graph import bigbang.process as process from bigbang.parse import get_date from bigbang.archive import Archive reload(process) import pandas as pd import datetime import matplotlib.pyplot as plt import numpy as ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import the BigBang modules as needed. These should be in your Python environment if you've installed BigBang correctly. Step2: Now let's load t...
2,263
<ASSISTANT_TASK:> Python Code: import time time.sleep(1000) lista = ['perro' ,'gato'] print(lista) lista[1] import numpy as np array_1 = np.array([3,4,5]) array_2 = np.array([4,8,7]) array_1 + array_2 array_1 = np.zeros(5) print(array_1) array_1[0] arreglo = np.random.randint(1,10,500000) np.mean(arreglo) arre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Resetear Step2: podemos agregar elementos Step3: o podemos usar el modulo Numpy para arreglos numericos (Protip Step4: y que tal arreglos vac...
2,264
<ASSISTANT_TASK:> Python Code: import os import logging import json from nis_util import do_large_image_scan, set_optical_configuration, get_position logging.basicConfig(format='%(asctime)s - %(levelname)s in %(funcName)s: %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) path_to_nis = 'C:\\Progr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: set paths Step2: do a dummy overview scan Step3: corresponding points Step4: save the calibration Step5: test the transformation
2,265
<ASSISTANT_TASK:> Python Code: from burnman import Composition olivine_composition = Composition({'MgO': 1.8, 'FeO': 0.2, 'SiO2': 1.}, 'weight') olivine_composition.print('molar', significant_figures=4, normalization_compon...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: After initialization, the "print" method can be used to directly print molar, weight or atomic amounts. Optional variables control the print pre...
2,266
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../') import numpy as np from anemoi import MiniZephyr, SimpleSource, AnalyticalHelmholtz import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Error plots for MiniZephyr vs. the AnalyticalHelmholtz response Step2: Relative error of the MiniZephyr solution (in %)
2,267
<ASSISTANT_TASK:> Python Code: Image("img/init.png") Image("img/target_result.png") # FOR WEB SCRAPING from lxml import html import requests # FOR FUNCTIONAL PROGRAMMING import cytoolz # pipe # FOR DATA WRANGLING import pandas as pd # use of R like dataframes import re #re for regular expressions # TO INSERT IMAGES ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Expected results Step2: Techniques used Step3: Data wrangling in action Step4: The extracted tree still contains much noise Step5: Use of la...
2,268
<ASSISTANT_TASK:> Python Code: !pip install tweepy import tweepy consumer_key='' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweets = api.home_timeline(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Assuming the installation worked, you can now import the tweepy module. Step2: The next step is to get a costomer_key, consumer_secret, access_...
2,269
<ASSISTANT_TASK:> Python Code: from numpy.random import standard_normal # Gaussian variables N = 1000; P = 5 X = standard_normal((N, P)) W = X - X.mean(axis=0,keepdims=True) print(dot(W[:,0], W[:,1])) from sklearn.decomposition import PCA S=PCA(whiten=True).fit_transform(X) print(dot(S[:,0], S[:,1])) from numpy.rand...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: I'll skip ahead and use a pre-canned PCA routine from scikit-learn (but I'll dig into it a bit later!) Let's see what happens to the transformed...
2,270
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.asarray([1,2,3,4]) pos = 2 element = 66 a = np.insert(a, pos, element) <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
2,271
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np def find_peaks(a): Find the indices of the local maxima in a sequence. leest = [] if a[0] > a[1]: leest.append(0) for x in range(1,len(a)-1): if (a[x-1]<a[x]) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Peak finding Step3: Here is a string with the first 10000 digits of $\pi$ (after the decimal). Write code to perform the following
2,272
<ASSISTANT_TASK:> Python Code: import pyalps lattice_range = [2, 3, 4, 5] parms = [{ 'LATTICE' : "open square lattice", # Set up the lattice 'MODEL' : "spinless fermions", # Select the model 'L' : L, # Lattice dimension 't' : -1 , ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For now, we are only interested in relatively small systems, we will try lattice sizes between $2\times 2$ and $5\times 5$. With this, we set th...
2,273
<ASSISTANT_TASK:> Python Code: aapl = data.DataReader('AAPL', 'yahoo', '2000-01-01') print(aapl.head()) plt.plot(aapl.Close) print(aapl['Adj Close'].head()) %matplotlib inline plt.plot(aapl['Adj Close']) plt.ylabel('price') plt.xlabel('year') plt.title('Price history of Apple stock') plt.show() ibm = data.DataReader(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: $\Rightarrow$ We get various different prices Step2: $\Longrightarrow$ There was a stock split 7 Step3: For the apple chart one can see, that ...
2,274
<ASSISTANT_TASK:> Python Code: # importamos la librería numpy, y le damos como nombre np dentro del programa import numpy as np lista=[25,12,15,66,12.5] vector=np.array(lista) print(vector) print("- vector original") print(vector) print("- sumarle 1 a cada elemento del vector:") print(vector+1) print("- multiplicar p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ahora que tenemos la librería, empecemos creando un vector de 5 elementos. Step2: ¿Cuál es la diferencia entre vector y lista? Que vector, al ...
2,275
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(type(a)) a L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(type(L)) L a = np.arange(1000) #arange : 그냥 array range임 array로 바꿈 %time a2 = a**2 a1 = np.arange(10) print(a1) print(2 * a1) L = range(1000) %time L2 = [i**2 for i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 만들어진 ndarray 객체의 표현식(representation)을 보면 바깥쪽에 array()란 것이 붙어 있을 뿐 리스트와 동일한 구조처럼 보인다. 실제로 0, 1, 2, 3 이라는 원소가 있는 리스트는 다음과 같이 만든다. Step2: 그러나 ndar...
2,276
<ASSISTANT_TASK:> Python Code: # Import useful libraries import numpy as np import pandas as pd # Import required libraries for data visualisation import matplotlib.pyplot as plt import seaborn as sns # Import the package import kinact # Magic %matplotlib inline # import data data_fc, data_p_value = kinact.get_example...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Quick Start Step2: 1. Loading the data Step3: 2. Import prior-knowledge kinase-substrate relationships from PhosphoSitePlus Step4: 3. KSEA St...
2,277
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend %matplotlib inline from __future__ import division, print_function from collections import defaultdict import os import numpy as np from scipy import optimize from scipy.stats import chisquare import...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Cosmic-ray composition effective area analysis Step2: Load simulation DataFrame and apply quality cuts Step3: Define energy binning for this a...
2,278
<ASSISTANT_TASK:> Python Code: import os from tqdm import tqdm from rmgpy import settings from rmgpy.data.rmg import RMGDatabase from rmgpy.kinetics import KineticsData from rmgpy.rmg.model import getFamilyLibraryObject from rmgpy.data.kinetics.family import TemplateReaction from rmgpy.data.kinetics.depository import D...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Steps Step1: 0. helper methods Step2: 1. load text-format fragment mech Step3: 2. get thermo and kinetics Step4: 2.1 correct entropy for certain fra...
2,279
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 16.0) import matplotlib.pyplot as plt import numpy as np import scipy as sp from scipy import fftpack from numpy import fft import json from functools import partial class Foo: pass from chest import Chest...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load a frame from a real simulation. Step2: Load the governing properties from the frame. Step3: Load the last midplane slice of the scalar fi...
2,280
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.stats import norm from thunder import SourceExtraction from thunder.extraction import OverlapBlockMerger import matplotlib.pyplot as plt %matplotlib inline from thunder import Colorize image = Colorize.image path = 's3://neuro.datasets/challenges/neurofinde...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup plotting Step2: Load data Step3: load and cache the raw data (we only load first 100 time points because we're on a single node) Step4: ...
2,281
<ASSISTANT_TASK:> Python Code: # First, we'll "import" the software packages needed. import pandas as pd import numpy as np %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt inline_rc = dict(mpl.rcParams) # Starting a line with a hashtag tells the program not to read the line. # That way we ca...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Raw data Step2: Plotting the data Step3: Calculate and plot velocity
2,282
<ASSISTANT_TASK:> Python Code: %matplotlib inline from bigbang.archive import Archive from bigbang.archive import load as load_archive import bigbang.parse as parse import bigbang.graph as graph import bigbang.mailman as mailman import bigbang.process as process import networkx as nx import matplotlib.pyplot as plt imp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set a valid date frame for building the network. Step2: Filter data according to date frame and export to .gexf file
2,283
<ASSISTANT_TASK:> Python Code: def lstrip(iterable, obj): stop = False for item in iterable: if stop: yield item elif item != obj: yield item stop = True x = lstrip([0, 1, 2, 3, 0], 0) x list(x) def lstrip(iterable, obj): lstrip_stop = F...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Bonus2 Step3: Unit Tests
2,284
<ASSISTANT_TASK:> Python Code: import os fileCount = len(os.walk('./texts').next()[2]) print(fileCount) print(os.walk('./texts').next()[2]) import glob import re files = {} for fpath in glob.glob("./texts/*.txt"): with open(fpath) as f: fixed_text = re.sub("[^a-zA-Z'-]"," ",f.read()) files[fpath] = (...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For the record, here are our texts Step2: Let's get some basic information about these texts
2,285
<ASSISTANT_TASK:> Python Code: [n for n in table.colnames if n.startswith('ks')] p = table['ttest:out_of_transit&before_midtransit-vs-out_of_transit&after_midtransit'] poorly_normalized_oot_threshold = -1 mask_poorly_normalized_oot = np.log(p) > poorly_normalized_oot_threshold plt.hist(np.log(p[~np.isnan(p)])) plt.axv...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If the distribution of fluxs before transit is significantly different from the distribution of fluxs after transit, mask those results. Step2: ...
2,286
<ASSISTANT_TASK:> Python Code: import SimpleITK as sitk # If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage # function so that it also resamples the image to a smaller size (testing environment is memory constrained). %run setup_for_testing # Utility method t...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Utility functions Step4: Loading Data Step5: Initial Alignment Step6: Look at the transformation, what type is it? Step7: Final registration...
2,287
<ASSISTANT_TASK:> Python Code: import pynmea2 msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D", check=True) msg msg.lat, msg.latitude, msg.latitude_minutes, msg.latitude_seconds msg.lon, msg.longitude, msg.longitude_minutes, msg.longitude_seconds pynmea2.parse("$GPVTG,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: GGA - GPS Fix Data Step2: The lat and lon attributes are in DDDMM.SSSSS format while latitude and longitude are their float values. Step3: VT...
2,288
<ASSISTANT_TASK:> Python Code: using React, Interact s = slider(0:0.01:1, label="Slider X:") signal(s) display(typeof(s)); isa(s, Widget) display(typeof(signal(s))); isa(signal(s), Signal{Float64}) s xsquared = lift(x -> x*x, signal(s)) using Color lift(x -> RGB(x, 0.5, 0.5), signal(s)) r = slider(0:0.01:1, label...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interact.jl provides interactive widgets for IJulia. Interaction relies on React.jl reactive programming package. React provides the type Signal...
2,289
<ASSISTANT_TASK:> Python Code: %matplotlib inline # we will use numpy and matplotlib for all the following examples import numpy as np import matplotlib import matplotlib.pyplot as plt def mexican_hat(x, mu, sigma): return 2 / (np.sqrt(3 * sigma) * np.pi**0.25) * (1 - x**2 / sigma**2) * np.exp(-x**2 / (2 * sigma**2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The mexican hat function/wavelet is the rescaled negative second derivative of the gaussian function (the probability distribution function of t...
2,290
<ASSISTANT_TASK:> Python Code: exp = butler.get("calexp", {"visit":903334, "detector":22, "instrument":"HSC"}) print(exp.getWcs()) wcs = butler.get("calexp.wcs", {"visit":903334, "detector":22, "instrument":"HSC"}) print(wcs) vinfo = butler.get("calexp.visitInfo", {"visit":903334, "detector":22, "instrument":"HSC"}) pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can get all data IDs/Dimensions. Step2: In Gen3, we can also get the WCS and the file URI without dumping the images as Python objects, for...
2,291
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from matplotlib.pyplot import show, plot import matplotlib.pyplot as plt # 初始化一个全0的数组来存放剩余资本 # 以参数10000调用binomial函数,进行10000轮硬币赌博游戏 cash = np.zeros(10000) cash[0] = 1000 outcome = np.random.binomial(9, 0.5, size=len(cash)) # 模拟每一轮抛硬币的结果,更新cash数组 # 打印出...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. 随机数 Step2: 2. 超几何分布 Step3: 3. 连续分布 Step4: 3.2 对数正态分布
2,292
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import statsmodels.formula.api as smf df_Obama = pd.read_csv("data/Fox_polls - Obama Job.csv") df_Iran_Deal = pd.read_csv("data/Fox_polls - Iran Deal.csv") df_Iran_Nego = pd.read_csv("data/Fox_polls - Iran Nego.csv") ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First for the Obama Love and Iran Deal Approval Step2: Now for Obama Love and Confidence in Negotiations with Iran
2,293
<ASSISTANT_TASK:> Python Code: !ipython nbconvert 'Working With Markdown Cells.ipynb' !ipython nbconvert --to=html 'Working With Markdown Cells.ipynb' !ipython nbconvert --to=latex 'Working With Markdown Cells.ipynb' !ipython nbconvert --to=latex 'Working With Markdown Cells.ipynb' --post=pdf pyfile = !ipython ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Html is the default value (that can be configured) , so the verbose form would be Step2: You can also convert to latex, which will take care of...
2,294
<ASSISTANT_TASK:> Python Code: # Import modules import random import numpy as np # Import PySwarms from pyswarms.single import GlobalBestPSO # Algorithm paramters random.seed(0) # The weight capacity of the knapsack capacity = 50 number_of_items = 10 item_range = range(number_of_items) value = [random.randint(1,numbe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Knapsack problem Step3: Early stopping using ftol Step4: Extending property using ftol_iter
2,295
<ASSISTANT_TASK:> 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 zipfil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this...
2,296
<ASSISTANT_TASK:> 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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: REINFORCE agent Step2: Hyperparameters Step3: Environment Step4: We can render this environment to see how it looks. A free-swinging pole is ...
2,297
<ASSISTANT_TASK:> Python Code: # system functions that are always useful to have import time, sys, os # basic numeric setup import numpy as np # inline plotting %matplotlib inline # plotting import matplotlib from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # seed the random number generator...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: One of the key assumptions of (Static) Nested Sampling is that we "shrink" according to Step2: We will now sample from this distribution using ...
2,298
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pylab as plt %matplotlib notebook import h5hep import pps_tools as pps filename = 'dimuons_1000_collisions.hdf5' pps.download_drive_file(filename) ### Other examples: ### #pps.download_file_from_google_drive('dimuons_1000_collisions.hdf5','data/file...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now we need the particle physics specific libraries. If you installed the libraries from the command shell properly as shown in the local setup ...
2,299
<ASSISTANT_TASK:> Python Code: import os import requests from datetime import datetime from clint.textui import progress import pandas pandas.set_option('display.float_format', lambda x: '%.2f' % x) pandas.set_option('display.max_columns', None) def download_csv(name): Accepts the name of a calaccess.download...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Download raw data Step3: Itemized receipts reported by campaigns Step5: Hack down RCPT_CD table outside of Python Step6: Concatenate them tog...