Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
3,400
<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: Environments Step9: Python Environments Step10: In addition to the step() method, environments also provide a reset() method that starts a new...
3,401
<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: Image classification with Model Garden Step2: Import TensorFlow, TensorFlow Datasets, and a few helper libraries. Step3: The tensorflow_models...
3,402
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.set_log_level("ERROR") ps.show_versions(numba=True, lmfit=True) head = pd.read_csv("data_wagna/head_wagna.csv", index_col=0, parse_dates=True, squeeze=True, skiprows=2).loc["...
<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. Read Data and plot autocorrelation Step2: 2. Run models with AR(1) noise model Step3: 3. Run models with ARMA(1,1) noise model Step4: 4. P...
3,403
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() x = 5 y = 10 z = x + y print (z) # affiche z x = 2 y = x + 1 print (y) x += 5 print (x) a = 0 for i in range (0, 10) : a = a + i # répète dix fois cette ligne print (a) a = 10 if a > 0 : print(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: Partie 1 Step2: On programme sert souvent à automatiser un calcul comme le calcul mensuel du taux de chômage, le taux d'inflation, le temps qu'...
3,404
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import keras import keras.backend as K from keras.layers import Conv2D from keras.models import Sequential %matplotlib inline inputs = np.random.randint(1, 9, size=(4, 4)) inputs def show_matrix(m, color, cmap, title=None): rows, co...
<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: Convolution Operation Step2: The matrix is visualized as below. The higher the intensity the bright the cell color is. Step3: We are using sm...
3,405
<ASSISTANT_TASK:> Python Code: def hello_world(): print('hello world') # wrap hello world in a function that does logging def wrap_hello(): print('Enter: hello_world') hello_world() print('Exit: hello_world') wrap_hello() # to wrap any function at all, write a generic wrapper that takes the 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: 2. Advanced Decorators Step2: 3. Metaclasses
3,406
<ASSISTANT_TASK:> Python Code: !rm -rf /tmp/ImageNetTrainTransfer #Import import pandas as pd import numpy as np import os import tensorflow as tf import random from PIL import Image #Inception preprocessing code from https://github.com/tensorflow/models/blob/master/slim/preprocessing/inception_preprocessing.py #useful...
<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: Lettura file words di ImageNet Step2: Aggiunta colonna di lunghezza del label (quante classi contiene ogni label). Step3: Train DF Step4: Pul...
3,407
<ASSISTANT_TASK:> Python Code: %pylab inline pylab.rcParams['figure.figsize'] = (6, 6) import datajoint as dj from pipeline.preprocess import * (dj.ERD.from_sequence([Prepare, Sync, ExtractRaw, Spikes])-1).draw() dj.ERD(Prepare).add_parts().draw() dj.ERD(ExtractRaw).add_parts().draw() Prepare.GalvoAverageFrame().h...
<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 preprocess schema extracts, aligns, and synchronizes multiphoton trace data from both galvo and AOD systems. Step2: Here are the main eleme...
3,408
<ASSISTANT_TASK:> Python Code: raw_dataset = pd.read_csv(source_path + "Speed_Dating_Data.csv") raw_dataset.head(3) raw_dataset_copy = raw_dataset #merged_datasets = raw_dataset.merge(raw_dataset_copy, left_on="pid", right_on="iid") #merged_datasets[["iid_x","gender_x","pid_y","gender_y"]].head(5) #same_gender = merge...
<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 exploration Step3: Data processing Step4: Feature engineering Step5: Modelling Step6: Variables selection Step7: Decision Tree Step8: ...
3,409
<ASSISTANT_TASK:> Python Code: %load_ext sql %sql mysql://studentuser:studentpw@mysqlserver/dognitiondb %sql USE dognitiondb %config SqlMagic.displaylimit=25 %%sql SELECT ct.created_at, DAYOFWEEK(ct.created_at) FROM complete_tests ct LIMIT 49, 200 %%sql SELECT ct.created_at, DAYOFWEEK(ct.created_at), CASE DAYOFWE...
<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: <img src="https Step2: Of course, the results of the query in Question 1 would be much easier to interpret if the output included the name of t...
3,410
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import numpy as np class Halley: def __init__(self, a): self.f = lambda x: a[0] + a[1] * x + a[2] * tf.pow(x, 2) + a[3] * tf.pow(x, 3) + a[4] * tf.pow(x, 4) self.df = lambda x: tf.gradients(self.f(x), x)[0] # TensorFlow does automatic differentiation! ...
<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: Iterate 3 times Step2: Iterate until condition
3,411
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import pyther as pt def main_eos(): print("-" * 79) components = ["METHANE"] MODEL = "PR" specification = "constants" component_eos = pt.parameters_eos_constans(components, MOD...
<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: Luego de hacer la importación de las librerías que se van a utilizar, en la función main_eos() definida por un usuario se realiza la especificac...
3,412
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array([1, 2, 3]) print(a) print('') b = np.array([(1, 2, 3), (4, 5, 6)]) print(b) a + b a * b b - a a**2 10*np.sin(a) # seno trigonométrico b<35 print('Axis 1: %s' % b[0]) print(np.average(b)) print(b.sum()) print(b.min()) print(b.max()) b.sum(axis=0) # sum of ea...
<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: Exercícios
3,413
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np file_name_string = 'C:/Users/Charles Kelly/Desktop/Exercise Files/02_07/Final/EmployeesWithGrades.xlsx' employees_df = pd.read_excel(file_name_string, 'Sheet1', index_col=None, na_values=['NA']) employees_df employees_df["Grade"] = employees_df["Gra...
<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: Change data type Step2: Rename the categories Step3: Values in data frame have not changed Step4: tabulate Department, Name, and YearsOfServi...
3,414
<ASSISTANT_TASK:> Python Code: from crpropa import * ## settings for MHD model (must be set according to model) filename_bfield = "clues_primordial.dat" ## filename of the magnetic field gridOrigin = Vector3d(0,0,0) ## origin of the 3D data, preferably at boxOrigin gridSize = 1024 #...
<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: to make use of periodicity of the provided data grid, use Step2: to not follow particles forever, use Step3: Uniform injection Step4: Injecti...
3,415
<ASSISTANT_TASK:> Python Code: import numpy as np # 数値計算を行うライブラリ import scipy as sp # 科学計算ライブラリ from scipy import stats # 統計計算ライブラリ significance = 0.05 o = [17, 10, 6, 7, 15, 5] # 実測値 e = [10, 10, 10, 10, 10, 10] # 理論値 chi2, p = stats.chisquare(o, f_exp = e) print('chi2 値は %(chi2)s' %locals()) print('確率は %(p)s' %local...
<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: <h2 STYLE="background Step2: <h4 style="padding Step3: <h2 STYLE="background Step4: <h4 style="padding Step5: <h4 style="border-bottom Step6...
3,416
<ASSISTANT_TASK:> Python Code: # ! pip install -u gremlinpython graphistry # ! pip install -u pandas # see https://rapids.ai/ if trying GPU dataframes ! pip show gremlinpython graphistry | grep 'Name\|Version' import graphistry graphistry.__version__ # To specify Graphistry account & server, use: # graphistry.registe...
<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: Imports Step2: Configure Step3: Connect Step4: Query & plot Step5: Customize your visuals & Embed Step6: Generate URL for other systems
3,417
<ASSISTANT_TASK:> Python Code: import tensorflow as tf a = tf.constant([1,2,3]) b = tf.constant([4,5,6,7]) def g(a,b): tile_a = tf.tile(tf.expand_dims(a, 1), [1, tf.shape(b)[0]]) tile_a = tf.expand_dims(tile_a, 2) tile_b = tf.tile(tf.expand_dims(b, 0), [tf.shape(a)[0], 1]) tile_b = tf.expand_dims(tile_b...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,418
<ASSISTANT_TASK:> Python Code: %matplotlib notebook # %matplotlib inline %matplotlib tk import os import pandas as pd import numpy as np import matplotlib.pyplot as plt os.getcwd() os.chdir('C:\\Users\\manolis\\Desktop\\PycharmProjects\\IRAS\\IRAS\\ref IR spectra') os.listdir() nist = pd.read_csv( 'guaiacol IR_solution...
<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 determined that the NIST data for Guaiacol (2-methoxyphenol) had 18 values that were zero in the transmittance data and therefore infinity wh...
3,419
<ASSISTANT_TASK:> Python Code: import os.path as op import mne data_path = mne.datasets.sample.data_path() fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True) print(evokeds) evoked = mne.read_evokeds(fname, condition='Left Auditory', ba...
<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 Step2: Notice that the reader function returned a list of evoked instances. This is Step3: If you're gone through the tutorials of raw an...
3,420
<ASSISTANT_TASK:> Python Code: from random import choice from time import sleep from rv.api import Pattern, Project, m, NOTE, NOTECMD from sunvox.api import init, Slot init(None, 44100, 2, 0) slot = Slot() project = Project() inst = project.output << project.new_module( m.AnalogGenerator, sustain=False, r...
<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: Initialize SunVox Step2: Create a project with an Analog Generator Step3: Create a tiny 4×4 pattern Step4: Randomize the notes in the pattern...
3,421
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s : str A string of characters. ...
<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: Character counting and entropy Step4: The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensivel...
3,422
<ASSISTANT_TASK:> Python Code: from quantopian.pipeline import Pipeline from quantopian.research import run_pipeline from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import SimpleMovingAverage mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length...
<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 this example, we need two factors Step2: Then, let's create a percent difference factor by combining our mean_close_30 factor with our mean...
3,423
<ASSISTANT_TASK:> Python Code: %%file example.py from mpi4py.MPI import COMM_WORLD as communicator import random # Draw one random integer between 0 and 100 i = random.randint(0, 100) print('Rank %d' %communicator.rank + ' drew a random integer: %d' %i ) # Gather the results integer_list = communicator.gather( i, root=...
<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: What happened? Step2: The code executes faster than the serial example, because each process has a smaller amount of work, and the two processe...
3,424
<ASSISTANT_TASK:> Python Code: import pandas df = pandas.read_csv('C:\\Users\\user\\Desktop\\TRABALHO-4.csv', sep=';') df tempo_medio = 1.1558 / 30 print("O tempo médio entre as chegadas à fila é", tempo_medio*60, "minutos.") taxa_de_chegada = 1 / tempo_medio print(taxa_de_chegada) pandas.DataFrame.mean(df['SAIDA-EN...
<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: Respostas Step2: d) A taxa de chegada de usuários no sistema Step3: $$\Lambda = 25.956\ clientes/hora$$ Step4: f) A taxa de atendimento dos u...
3,425
<ASSISTANT_TASK:> Python Code: # Authors: Jeff Hanna <jeff.hanna@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import refmeg_noise from mne.preprocessing import ICA import numpy as np print(__doc__) data_path = refmeg_noise.data_path() raw_fname = data_path + '/sample_reference...
<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: Read raw data, cropping to 5 minutes to save memory Step2: Note that even though standard noise removal has already Step3: The PSD of these da...
3,426
<ASSISTANT_TASK:> Python Code: %matplotlib inline from selenium import webdriver import os,time,json import pandas as pd from collections import defaultdict,Counter import matplotlib.pyplot as plt url = "http://www.imdb.com/list/ls061683439/" with open('./filmfare.json',encoding="utf-8") as f: datatbl = json.load(...
<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: Getting Data Step2: Store Data in a Python Dictionary Step3: Data before Clean Up Step4: Clean Data Step5: How does data in Dictionary look...
3,427
<ASSISTANT_TASK:> Python Code: #Compute x = 4 * 3 and print the result x = 4 * 3 print(x) #Compute y = 6 * 9 and print the result y = 6 * 9 print(y) # Import the Pandas library import pandas as pd kaggle_path = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/" # Load the train and test datasets to create tw...
<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: 2. Get the Data with Pandas Step2: 3.Understanding your data Step3: 4. Rose vs Jack, or Female vs Male Step4: 5.Does age play a role? Step5: ...
3,428
<ASSISTANT_TASK:> Python Code: x=1 print x type(x) x.conjugate() type(1+2j) z=1+2j print z (1,2) t=(1,2,"text") t t def foo(): return (1,2) x,y=foo() print x print y def swap(x,y): return (y,x) x=1;y=2 print "{0:d} {1:d}".format(x,y) x,y=swap(x,y) print "{:f} {:f}".format(x,y) dir(1) x=[] x.append("text") x x.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: if/else, for, while, pass, break, continue Step2: List Step3: Dictionary Step4: Function Step5: Module
3,429
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import pandas as pd pd.options.display.max_rows = 999 pd.set_option('display.width', 1000) import glob header = ["evaluation_type", "dataset", "kwargs", "evaluation", "value", "num_skipped"] similarity_dfs = [] similarity_names = [] similarity_glob = ...
<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: Similarity task Step2: Analogy task Step3: We then present the results using the threecosadd analogy function. Step4: Bigger Analogy Test Set...
3,430
<ASSISTANT_TASK:> Python Code: # import packages import phylogenetics as phy import phylogenetics.tools as tools import phylopandas as ph import pandas as pd from phylovega import TreeChart # intitialize project object and create project folder project = phy.PhylogeneticsProject(project_dir='tutorial', overwrite=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: 1. Inititialize a phylogenetics project Step2: 2. Read in your starting sequence(s) Step3: 3. Use BLAST to search for orthologs similar to you...
3,431
<ASSISTANT_TASK:> Python Code: # remove display of install details %%capture --no-display !pip install ipyparallel import subprocess subprocess.Popen(['ipcluster', 'start', '-n', '4']) # authorize Google to access Google drive files !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive impor...
<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: End of Warning Step2: Problem 1) Light Curve Data Step3: As we have many light curve files (in principle as many as 37 billion...), we will de...
3,432
<ASSISTANT_TASK:> Python Code: # Authors: Remi Flamary <remi.flamary@unice.fr> # Stanislas Chambon <stan.chambon@gmail.com> # # License: MIT License import numpy as np import matplotlib.pylab as pl import ot n_source_samples = 100 n_target_samples = 100 theta = 2 * np.pi / 20 noise_level = 0.1 Xs, ys = ot.dat...
<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 data Step2: Plot data Step3: Instantiate the different transport algorithms and fit them Step4: Plot transported samples
3,433
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import warnings warnings.filterwarnings('ignore') import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd from load_utils import * d = load_diffs(keep_diff = True) df_events, df_blocked_user_text = ...
<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: Q Step2: Model does not assign 0 scores, like the annotators. Step3: Q Step4: Q Step5: Q
3,434
<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: 날씨 데이터세트 Step3: 이 튜토리얼은 시간별 예측만 다루므로 10분 간격부터 1시간까지 데이터를 서브 샘플링하는 것으로 시작합니다. Step4: 데이터를 살펴보겠습니다. 다음은 처음 몇 개의 행입니다. Step5: 시간이...
3,435
<ASSISTANT_TASK:> Python Code: class Point(): Holds on a point (x,y) in the plane def __init__(self, x=0, y=0): assert isinstance(x, (int, float)) and isinstance(y, (int, float)) self.x = float(x) self.y = float(y) p = Point(1,2) print("point", p.x, p.y) origin = Point() print("orig...
<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: Classes Step2: Notice that when we send a Point to the console we get Step4: Which is not useful, so we will define how Point is represented i...
3,436
<ASSISTANT_TASK:> Python Code: !sequana_coverage --download-reference FN433596 ! art_illumina -sam -i FN433596.fa -p -l 100 -ss HS20 -f 20 -m 500 -s 40 -o paired_dat -f 100 # no need for the *aln and *sam, let us remove them to save space !rm -f paired*.aln paired_dat.sam !sequana_mapping --reference FN433596.fa --fi...
<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: Simulated FastQ data Step2: Creating the BAM (mapping) and BED files Step3: This uses bwa and samtools behind the scene. Then, we will convert...
3,437
<ASSISTANT_TASK:> Python Code: try: n = int(input("Enter n: ")) if n > 0: q = 1 elif n == 0: q = 2 else: q = 3 except: q = 4 n = int(input("Enter n: ")) if n > 0: q = 1 if n >10: q = 2 if n > 20: q = 3 else: q = 4 a = 10 b = "15" c = 10.5 w = a + c...
<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. 1 Step2: a. 1 Step3: a. 4 Step4: a. 4 Step5: Functions, continued Step6: dir() and help() built-in functions Step7: Watch Me Code 1 Ste...
3,438
<ASSISTANT_TASK:> Python Code: from IPython import display display.Image('img/simple.jpg', width=400) import random import math import numpy from string import Template from deap import base from deap import creator from deap import tools from deap import algorithms from lily_template import TEMPLATE # Global Variabl...
<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: Will be rempresented as Step2: The file lily_template has the template to create the lilypond file and to give it format I used the string.Temp...
3,439
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) def complete_deg(n): Return the integer valued degree matrix D for the complete graph K_n. D = np.diag([n-1 for i in range(n)])...
<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: Complete graph Laplacian Step3: The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defi...
3,440
<ASSISTANT_TASK:> Python Code: from coherence import load_coherence_dataset coherence_ds = load_coherence_dataset() X = coherence_ds.data y = coherence_ds.target from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=1) 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: Train-Test Split Step2: K-fold Cross Validation and HyperParameter Tuning Step3: Setting HyperParameters to tune Step4: Show HyperParameters ...
3,441
<ASSISTANT_TASK:> Python Code: # import the standard numerical and plotting packages import matplotlib.pyplot as plt import numpy as np from skimage.io import imread # load the images a = imread("B005_1.tif") b = imread("B005_2.tif") fig, axs = plt.subplots(1, 2, figsize=(9, 4)) axs[0].imshow(a, cmap=plt.cm.gray) axs[...
<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 have downloaded some sample images from PIV challenge, Step2: The two images show the positions of the particles at two different times. We...
3,442
<ASSISTANT_TASK:> Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) # Importando um módulo em Python import math # Verificando todos os métodos disponíveis no módulo dir(math) # Usando um dos métodos do módu...
<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: Módulos e Pacotes
3,443
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('..') import socnet as sn sn.graph_width = 320 sn.graph_height = 180 g = sn.load_graph('4-dijkstra.gml', has_pos=True) for n, m in g.edges(): g.edge[n][m]['label'] = g.edge[n][m]['c'] sn.show_graph(g, elab=True) class Heap(object): def __init__(self, ...
<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 seguir, vamos configurar as propriedades visuais Step2: Por fim, vamos carregar e visualizar um grafo Step3: Algoritmo de Dijkstra Step4: E...
3,444
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import matplotlib.colors as colors filename = '../facies_vectors.csv' training_data = pd.read_csv(filename) training_data ...
<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 Preparation and Model Selection Step2: The accuracy function and accuracy_adjacent function are defined in teh following to quatify the pr...
3,445
<ASSISTANT_TASK:> Python Code: #INPUT #folder = 'sample' # create this folder and place the exported file folder = 'all' #export_filename = 'English_Vocabulary_Sample.csv' export_filename = 'English_Vocabulary3.csv' Generate a dictionary from Anki export file. Note: Only GRE words have proper Serial No. Rest words have...
<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: CSV export file manipulations Step5: Copying media files to folders Step7: Sort the columns Step13: GRE words only
3,446
<ASSISTANT_TASK:> Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Execute this cell to enable verbose SSH commands logging.getLogger('ssh').setLevel(logging.DEBUG) # Other python modules required by this notebook import json import os # Setup a target configuration conf = { # Ta...
<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: <br><br><br><br> Step2: Commands execution on remote target Step3: Example of frameworks configuration on remote target Step4: Create a big/L...
3,447
<ASSISTANT_TASK:> Python Code: fifteen_factorial = 15*14*13*12*11*10*9*8*7*6*5*4*3*2*1 print(fifteen_factorial) import math print(math.factorial(15)) print("Result correct?", math.factorial(15) == fifteen_factorial) print(math.factorial(5), math.sqrt(2*math.pi)*5**(5+0.5)*math.exp(-5)) print(math.factorial(10), math....
<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: Exercise 2 Step2: Exercise 3 Step4: We see that the relative error decreases, whilst the absolute error grows (significantly). Step6: In late...
3,448
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt a_true = 0.5 b_true = 2.0 c_true = -4.0 def quad(x,a,b,c): return a*x**2 + b*x + c N = 30 xdata = np.linspace(-5,5,N) dy = 2.0 np.random.seed(0) ydata = quad(xdata,a_true,b_true,c_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: Fitting a quadratic curve Step2: First, generate a dataset using this model using these parameters and the following characteristics Step3: No...
3,449
<ASSISTANT_TASK:> Python Code: import glob from IPython.display import Image import numpy as np import openmc # 1.6 enriched fuel fuel = openmc.Material(name='1.6% Fuel') fuel.set_density('g/cm3', 10.31341) fuel.add_nuclide('U235', 3.7503e-4) fuel.add_nuclide('U238', 2.2625e-2) fuel.add_nuclide('O16', 4.6007e-2) # bor...
<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 Input Files Step2: With our three materials, we can now create a materials file object that can be exported to an actual XML file. Ste...
3,450
<ASSISTANT_TASK:> Python Code: PROJECT = 'cloud-training-demos' # Replace with your PROJECT BUCKET = 'cloud-training-bucket' # Replace with your BUCKET REGION = 'us-central1' # Choose an available region for Cloud MLE import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGIO...
<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: Exploring the data Step2: Define features Step3: Train a model in BigQuery Step4: With the demo dataset ready, it is possible to create a lin...
3,451
<ASSISTANT_TASK:> Python Code: %%bash export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT %%bash pip install tensorflow==2.6.0 --user import os PROJECT = "qwiklabs-gcp-bdc77450c97b4bf6" # REPLACE WITH YOUR PROJECT NAME REGION = "us-central1" # R...
<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 make sure we install the necessary version of tensorflow. After doing the pip install above, click Restart the kernel on the notebook so t...
3,452
<ASSISTANT_TASK:> Python Code: bigdf = pandas.read_csv('/media/notconfusing/9d9b45fc-55f7-428c-a228-1c4c4a1b728c/home/maximilianklein/snapshot_data/2016-01-03/gender-index-data-2016-01-03.csv') gender_qid_df = bigdf[['qid','gender']] def map_gender(x): if isinstance(x,float): return 'no gender' else: ...
<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: Rel risk. P(gender|misaligned)/P(gender)
3,453
<ASSISTANT_TASK:> Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) # Exercício 1 - Imprima na tela os números de 1 a 10. Use uma lista para armazenar os números. # Exercício 2 - Crie uma lista de 5 objetos ...
<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: Exercícios Cap02
3,454
<ASSISTANT_TASK:> Python Code: import gensim, logging, os logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) class Corpus(object): '''Clase Corpus que permite leer de manera secuencial un directorio de documentos de texto''' def __init__(self, directorio): ...
<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: Entrenamiento de un modelo Step2: CORPUSDIR contiene una colección de noticias en español (normalizada previamente a minúsculas y sin signos de...
3,455
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.stats import norm from clintrials.dosefinding.efftox import EffTox, LpNormCurve, efftox_dtp_detail from clintrials.dosefinding.efficacytoxicity import dose_transition_pathways, print_dtps real_doses = [7.5, 15, 30, 45] trial_size = 30 cohort_size = 3 first_do...
<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 above parameters are explained in the manuscript. Step2: The EffTox class is an object-oriented implementation of the trial design by Thall...
3,456
<ASSISTANT_TASK:> Python Code: from __future__ import division from terminaltables import AsciiTable import inet inet.__version__ from inet import DataLoader mydataset = DataLoader('../../data/PV') # create an object with information of all connections len(mydataset.experiment) mydataset.nIN, mydataset.nPC # number o...
<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: <H2>Object creation</H2> Step2: <H2>Object atttributes</H2> Step3: Details of every experiments are given in a list Step4: and details fo the...
3,457
<ASSISTANT_TASK:> Python Code: from owslib.iso import namespaces # Append gmi namespace to namespaces dictionary. namespaces.update({"gmi": "http://www.isotc211.org/2005/gmi"}) namespaces.update({"gml": "http://www.opengis.net/gml/3.2"}) # Select RA RAs = { "GLOS": "Great Lakes Observing System", "SCCOOS": "So...
<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 select a Regional Association Step2: Next we generate a geoportal query and georss feed Step3: Time to query the portal and parse out t...
3,458
<ASSISTANT_TASK:> Python Code: from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, Activation, add, Lambda from keras.layers.normalization import BatchNormalization from keras.layers.pooling import GlobalAveragePooling2D from keras.optimizers import RMSprop from keras.backend import tf as ktf from ker...
<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: Read the MNIST data. Notice that we assume that it's 'kaggle-DigitRecognizer/data/train.csv', and we use helper function to read into a dictiona...
3,459
<ASSISTANT_TASK:> Python Code: def net_force(mass, acceleration): return mass * acceleration # Function as above, but with DOCUMENTATION def net_force(mass, acceleration): Calculates f=ma, returns force. We assume mass, acceleration are of type int/float. return mass * acceleration def add(...
<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: I argued that one of the main drawbacks of this code is that "[it] implicitly assumes the user knows to pass in numbers". In this lecture I aim ...
3,460
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import requests from windpowerlib import ModelChain, WindTurbine, create_power_curve from windpowerlib import data as wt import logging logging.getLogger().setLevel(logging.DEBUG) def get_weather_data(filename='weather.csv', **kwargs): r Imports wea...
<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: You can use the logging package to get logging messages from the windpowerlib. Change the logging level if you want more or less messages. Step3...
3,461
<ASSISTANT_TASK:> Python Code: !pip install --upgrade --user pixiedust !pip install --upgrade --user pixiedust-flightpredict import pixiedust_flightpredict pixiedust_flightpredict.configure() from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.linalg import Vectors from numpy import array import nump...
<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: <h3>If PixieDust was just installed or upgraded, <span style="color Step2: Train multiple classification models Step3: Evaluate the models Ste...
3,462
<ASSISTANT_TASK:> Python Code: record_f = open("Sample_Data/Swim_Records/record_list.txt") record = record_f.read().decode('utf-8').split('\n') record_f.close() for line in record: print(line) from __future__ import print_function record_f = open("Sample_Data/Swim_Records/record_list.txt", 'r') record = record_f.r...
<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: 이제 평택의 정...
3,463
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt plt.ion() from astropy import time from poliastro.twobody.orbit import Orbit from poliastro.bodies import Earth from poliastro.plotting import OrbitPlotter from poliastro.neos import neows eros = neows.orbit_from_name('Eros') frame = OrbitPlotter() frame.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: NeoWS module Step2: You can also search by IAU number or SPK-ID (there is a faster neows.orbit_from_spk_id() function in that case, although) S...
3,464
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-2', 'toplevel') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<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...
3,465
<ASSISTANT_TASK:> Python Code: import os os.chdir('..') os.getcwd() !{'dpp'} !{'dpp run --verbose ./committees/kns_committee'} KNS_COMMITTEE_DATAPACKAGE_PATH = './data/committees/kns_committee/datapackage.json' from datapackage import Package kns_committee_package = Package(KNS_COMMITTEE_DATAPACKAGE_PATH) kns_commi...
<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: List the available pipelines Step2: Run a pipeline Step3: Inspect the output datapackage descriptor Step4: Each package may contain multiple ...
3,466
<ASSISTANT_TASK:> Python Code: qubits = [] for i in range(3): q = qubit.Qubit('Transmon') q.C_g = 3.87e-15 q.C_q = 75.1e-15 q.C_resToGnd = 79.1e-15 qubits.append(q) q = qubit.Qubit('OCSQubit') q.C_g = 2.94e-15 q.C_q = 48.5e-15 q.C_resToGnd = 51.5e-15 qubits.append(q) cpw = cpwtools.CPW(material='al...
<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: CPW Step2: $\lambda/4$ readout resonators Step3: Qubit parameters Step4: Feedline with and without crossovers Step5: Inductive Coupling Step...
3,467
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD-3-Clause from functools import partial import numpy as np from scipy import stats import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa, analysis:ignore import mne from mne.stats import (ttest_1samp_...
<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: Hypothesis testing Step2: The data averaged over all subjects looks like this Step3: In this case, a null hypothesis we could test for each vo...
3,468
<ASSISTANT_TASK:> Python Code: import math print("The square root of 3 is:", math.sqrt(3)) print("π is:", math.pi) print("The sin of 90 degrees is:", math.sin(math.radians(90))) math. math.erf? s = "Hello!" s.join() # or press <shift>+<tab> inside the brackets from IPython.display import Image Image('imgs/leonardo.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: Exploring modules -- getting help Step2: To get help with a particular function, type math.sin? Step4: A notebook can display (nearly) anythin...
3,469
<ASSISTANT_TASK:> Python Code: a = { "x" : 1, "y" : 2, "z" : 3 } b = { "w" : 10, "x" : 11, "y" : 2 } # Find keys in common a.keys() & b.keys() # Find keys in a that are not in b a.keys() - b.keys() # Find (key,value) pairs in common a.items() & b.items() # Make a new dictionary with certain ke...
<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: 为了寻找两个字典的相同点,可以简单的在两字典的 keys() 或者 items() 方法返回结果上执行集合操作。比如: Step2: 这些操作也可以用于修改或者过滤字典元素。 比如,假如你想以现有字典构造一个排除几个指定键的新字典。 下面利用字典推导来实现这样的需求:
3,470
<ASSISTANT_TASK:> Python Code: index_of_users = mkUserIndex(df=apps, user_col='uid') index_of_items = mkItemIndex(df=apps, item_col='job_title') print('# users: %d' %len(user_ids)) print('# job titles: %d' %len(item_ids)) from scipy.io import * user_apply_job = mmread(DATA_DIR + 'user_apply_job.mtx') printInfo(user_app...
<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: Applicant-apply-(Job, Employer) matrix
3,471
<ASSISTANT_TASK:> Python Code: indexfile = "./datafiles/index_latest.txt" import numpy as np dataindex = np.genfromtxt(indexfile, skip_header=6, unpack=True, delimiter=',', dtype=None, \ names=['catalog_id', 'file_name', 'geospatial_lat_min', 'geospatial_lat_max', 'geospatial_lon_min...
<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: To read the index file (comma separated values), we will try with the genfromtxt function. Step2: Map of observations Step3: We import the mod...
3,472
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers raw_inputs = [ [711, 632, 71], [73, 8, 3215, 55, 927], [83, 91, 1, 645, 1253, 927], ] # By default, this will pad using 0s; it is configurable via the # "value" paramet...
<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: Introduction Step2: Masking Step3: As you can see from the printed result, the mask is a 2D boolean tensor with shape Step4: This is also the...
3,473
<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: Introduction to OpenFermion Step2: Initializing the FermionOperator data structure Step3: The preferred way to specify the coefficient in open...
3,474
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import control as ct import control.optimal as opt ct.use_fbs_defaults() def vehicle_update(t, x, u, params): # Get the parameters for the model a = params.get('refoffset', 1.5) # offset to vehicle reference point b = ...
<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: Vehicle steering dynamics (Example 3.11) Step2: Vehicle driving on a curvy road (Figure 8.6a) Step3: Linearization of lateral steering dynamic...
3,475
<ASSISTANT_TASK:> Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Luke Bloy <luke.bloy@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op from mne.filter import next_fast_len import mne print(__doc__) data_path = mne.datasets.opm.dat...
<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 data, resample. We will store the raw objects in dicts with entries Step2: Do some minimal artifact rejection just for VectorView data Ste...
3,476
<ASSISTANT_TASK:> Python Code: from IPython.parallel import Client, error cluster = Client(profile='mpi') view = cluster[:] %%px from mpi4py import MPI mpi = MPI.COMM_WORLD bcast = mpi.bcast barrier = mpi.barrier rank = mpi.rank print "MPI rank: %i/%i" % (mpi.rank,mpi.size) %%px import sys from proteus.iproteus impor...
<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: IPython Parallel "Magics" Step2: Load Proteus Step3: Define the tank geometry Step4: Physics and Numerics Step5: Numerical Solution Object S...
3,477
<ASSISTANT_TASK:> Python Code: import re # Regular Expressions import pandas as pd # DataFrames & Manipulation import nltk.data # Sentence tokenizer from nltk.corpus import stopwords # Import the stop word list from bs4 import BeautifulSoup # HTML processi...
<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 text processing Step4: Define functions for cleaning the text data. Step5: Initialize and train the model Step6: Save the model for l...
3,478
<ASSISTANT_TASK:> Python Code: ### Load in necessary libraries for data input and normalization %matplotlib inline import numpy as np import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 from my_answers import * %load_ext autoreload %autoreload 2 from my_answers import * ### load in and normalize the data...
<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: Lets take a quick look at the (normalized) time series we'll be performing predictions on. Step2: 1.2 Cutting our time series into sequences S...
3,479
<ASSISTANT_TASK:> Python Code: import stripy as stripy import numpy as np xmin = 0.0 xmax = 10.0 ymin = 0.0 ymax = 10.0 extent = [xmin, xmax, ymin, ymax] spacingX = 0.5 spacingY = 0.5 ellip0 = stripy.cartesian_meshes.elliptical_mesh(extent, spacingX, spacingY, refinement_levels=0) ellip1 = stripy.cartesian_meshes.elli...
<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: Uniform meshes by refinement Step2: Refinement strategies Step3: Visualisation of refinement strategies Step4: Targetted refinement Step5: V...
3,480
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') import os import pathlib import matplotlib.pyplot as plt import numpy as np from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter from landlab.data_record import DataRecord from landlab.grid.network import Network...
<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. Load a shapefile that represents the river network Step2: Alright, let's see what fields we read in with this shapefile Step3: Great! Looks...
3,481
<ASSISTANT_TASK:> Python Code: #!/usr/bin/python %matplotlib inline import numpy as np import matplotlib.pyplot as plt from stats import parse_results, get_percentage, get_avg_per_seed, draw_pie, draw_bars, draw_bars_comparison, draw_avgs pr, eigen, bet = parse_results('test_ws.txt') draw_pie(get_percentage(pr)) dra...
<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: Parse results Step2: PageRank Seeds Percentage Step3: Avg adopters per seed comparison Step4: Eigenvector Seeds Percentage Step5: Avg adopte...
3,482
<ASSISTANT_TASK:> Python Code: import csv as csv csv_file_object = csv.reader(open('titanic_train.csv', 'rb')) header = csv_file_object.next() print(header) lines = [line for line in csv_file_object] print(lines[0]) print(lines[1]) import pandas as pd titanic_train = pd.read_csv("titanic_train.csv") titanic_train com...
<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: Use pandas! Step2: Community health status from data.gov Step3: -9999 Indicate N.A. value from the source data for the Unemployed column on th...
3,483
<ASSISTANT_TASK:> Python Code:: # map an integer to a word def word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return None # generate a description for an image def generate_desc(model, tokenizer, photo, max_length): # seed the generation proces...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,484
<ASSISTANT_TASK:> Python Code: import numpy as np rng = np.random.RandomState(42) x = rng.rand(1000000) y = rng.rand(1000000) %timeit x + y %timeit np.fromiter((xi + yi for xi, yi in zip(x, y)), dtype=x.dtype, count=len(x)) mask = (x > 0.5) & (y < 0.5) tmp1 = (x > 0.5) tmp2 = (y < 0.5) mask = tmp1 & tmp2 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: As discussed in Computation on NumPy Arrays Step2: But this abstraction can become less efficient when computing compound expressions. Step3: ...
3,485
<ASSISTANT_TASK:> Python Code: df['Total day minutes'].hist(); sns.boxplot(df['Total day minutes']); df.hist(); df['State'].value_counts().head() df['Churn'].value_counts() sns.countplot(df['Churn']); sns.countplot(df['State']); sns.countplot(df[df['State'].\ isin(df['State'].value_counts().head().ind...
<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.2. Категориальные Step2: 2. Взаимодействия признаков Step3: 2.2. Количественный с категориальным Step4: 2.3. Категориальный с категориальн...
3,486
<ASSISTANT_TASK:> Python Code: import psyplot.project as psy import xarray as xr %matplotlib inline %config InlineBackend.close_figures = False import numpy as np x = np.linspace(-1, 1.) y = np.linspace(-1, 1.) x2d, y2d = np.meshgrid(x, y) z = - x2d**2 - y2d**2 ds = xr.Dataset( {'z': xr.Variable(('x', 'y'), z)}, ...
<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 create some sample data in the form of a 2D parabola Step2: For a simple 2D plot of a scalar field, we can use the Step3: The plot fo...
3,487
<ASSISTANT_TASK:> Python Code: import graphlab people = graphlab.SFrame('people_wiki.gl/') people.head() len(people) obama = people[people['name'] == 'Barack Obama'] obama obama['text'] clooney = people[people['name'] == 'George Clooney'] clooney['text'] obama['word_count'] = graphlab.text_analytics.count_words(ob...
<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 some text data - from wikipedia, pages on people Step2: Data contains Step3: Explore the dataset and checkout the text it contains Step4:...
3,488
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline # This code translate from a binary number using the prefix "0b" to a base 10 number. int('0b11', 2) # This code translate from base 10 to base 2. bin(9) # Just looking a large binary number bin(2**53) import bitstrin...
<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: <div id='intro' /> Step2: <div id='nature' /> Step3: The next two functions are self-explanatory Step4: So if we compute gap(1) we should get...
3,489
<ASSISTANT_TASK:> Python Code: %pdb on %pdb def pick_and_take(): picked = numpy.random.randint(0, 1000) raise NotImplementedError() pick_and_take() import pdb;pdb.set_trace() def func(x): return x + 1 for i in range(100): print(func(i)) if i == 10 or i == 20: import pdb;pdb.set_trace() raise Exception...
<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: Tracer Step2: Interactive Python Console Step3: Pixie Debugger
3,490
<ASSISTANT_TASK:> Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) ...
<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: Changepoint Detection Step2: Likelihood Step4: Doing it the long way Step5: Using emcee Step6: Based on an example from Chapter 1 of Bayesia...
3,491
<ASSISTANT_TASK:> Python Code: from sympy import * from sympy.vector import CoordSys3D N = CoordSys3D('N') x1, x2, x3 = symbols("x_1 x_2 x_3") alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3") L, ga, gv, c = symbols("L g_a g_v c") init_printing() x = alpha1 y = alpha2 a1=gv *2*pi/L z = ga * cos(c * alpha1) r...
<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: Coordinates Step2: Mid-surface coordinates is defined with the following vector $\vec{r}=\vec{r}(\alpha_1, \alpha_2)$ Step3: Tangent to curve ...
3,492
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab import scipy.io as sio import math n=100 # number of iterations #initial B=0.15 # Model Noise R=0.02 # Observation Noise A = 0.5 # Model Matrix # creation of numpy arrays for variables z= np.zeros(n) m= np...
<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: Lorenz equations
3,493
<ASSISTANT_TASK:> Python Code: # Importa la librería financiera. # Solo es necesario ejecutar la importación una sola vez. import cashflows as cf import cashflows as cf ## ## Se tienen cuatro fuentes de capital con diferentes costos ## sus datos se almacenarar en las siguientes listas: ## monto = [0] * 4 interes = [...
<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: Problema del costo de capital Step2: En la modelación de créditos con cashflow se consideran dos tipos de costos
3,494
<ASSISTANT_TASK:> Python Code: from collections import OrderedDict #JSON to store all the informacion. jsonsOccupants = [] #Number of occupants N = 3 #Definition of the states states = OrderedDict([('Leaving','out'), ('Resting', 'sofa'), ('Working in my laboratory', 'wp')]) #Definition of the schedule schedule = {'t1':...
<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: 2.- We define the building plan or the distribution of the space. Step2: 3.- We implement a Model inheriting a base class of SOBA. Step3: 4.- ...
3,495
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML input_form = <div style="background-color:gainsboro; border:solid black; width:300px; padding:20px;"> Variable Name: <input type="text" id="var_name" value="foo"><br> Variable Value: <input type="text" id="var_value" value="bar"><br> <button onclick="set_...
<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: IPython Notebook Step3: After pressing <button>Set Value</button> above Step4: Examining the code, we see that Step7: And then we'll manipula...
3,496
<ASSISTANT_TASK:> Python Code: import os import sys sys.path.insert(0, "../..") import importlib import numpy as np import pandas as pd import yellowbrick import yellowbrick as yb from yellowbrick.features.importances import FeatureImportances import matplotlib as mpl import matplotlib.pyplot as plt from sklearn 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: Load Iris Datasets for Example Code Step2: Logistic Regression with Mean of Feature Importances Step3: Logistic Regression with Stacked Featur...
3,497
<ASSISTANT_TASK:> Python Code: class vector_math: ''' This is the base class for vector math - which allows for initialization with two vectors. ''' def __init__(self, vectors = [[1,2,2],[3,4,3]]): self.vect1 = vectors[0] self.vect2 = vectors[1] def set_vects(self, vect...
<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: Other vector operations that could be done Step2: List Comprehensions are Powerful tools in Python
3,498
<ASSISTANT_TASK:> Python Code: user = #type CMEMS user name within colons password = #type CMEMS password within colons product_name = 'INSITU_BAL_NRT_OBSERVATIONS_013_032' #type aimed CMEMS in situ product distribution_unit = 'cmems.smhi.se' #type aimed hosting institution index_file = 'index_latest.txt' #type aimed...
<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: <h3>DOWNLOAD</h3> Step2: <h3>QUICK VIEW</h3> Step3: <h3>FILTERING CRITERIA</h3> Step4: Regarding the above glimpse, it is posible to filter b...
3,499
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn.svm import SVR from sklearn.linear_model import Lasso from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split # input data reading df = pd.rea...
<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: Regression sample