Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
6,700
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import sys import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import flopy from flopy.utils.gridgen import Gridgen print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__versio...
<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 Base MODFLOW Grid Step2: Create the Gridgen Object Step3: Add an Optional Active Domain Step4: Refine the Grid Step5: Plot the Gridgen...
6,701
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.stats amean = -0.0896 avar = 0.954 anobs = 40 bmean = 0.719 bvar = 11.87 bnobs = 50 _, p_value = scipy.stats.ttest_ind_from_stats(amean, np.sqrt(avar), anobs, bmean, np.sqrt(bvar), bnobs, equal_var=False) <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:
6,702
<ASSISTANT_TASK:> Python Code: import warnings # Suppresing warnings for a "pretty output." warnings.simplefilter("ignore") %%writefile config.yaml # Specify a YYYY-MM-DD hh:mm:ss date or integer day offset. # If both start and stop are offsets they will be computed relative to datetime.today() at midnight. # Use 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: This notebook is quite big and complex, Step2: We'll print some of the search configuration options along the way to keep track of them. Step3:...
6,703
<ASSISTANT_TASK:> Python Code: def shout(word="yes"): return word.capitalize()+"!" shout() # As an object, you can assign the function to a variable like any other object scream = shout # Notice we don't use parentheses: we are not calling the function, # we are putting the function "shout" into the variable "scre...
<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: Functions inside another functions Step2: Function references Step3: With getTalk() we return the shout function and then with ("HellO"), we p...
6,704
<ASSISTANT_TASK:> Python Code: # Author: Denis A. Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import os import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline 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: Set parameters Step2: Compute inverse solution Step3: Decoding in sensor space using a logistic regression Step4: To investigate weights, we ...
6,705
<ASSISTANT_TASK:> Python Code: # Antes de tudo, importamos o pacote matemático numpy # que nos permite manipular matrizes e vetores. import numpy as np # Declaramos uma função onde colocaremos todo o código # para integração de Euler, que poderemos invocar facilmente # sempre que quisermos integrar numericamente uma e...
<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: Escrever uma descrição para documentar nossas funções logo abaixo da sua declaração nos permite extrair informações delas utilizando o comando h...
6,706
<ASSISTANT_TASK:> Python Code: x1 = np.random.uniform(size=500) x2 = np.random.uniform(size=500) fig = plt.figure(); ax = fig.add_subplot(1,1,1); ax.scatter(x1,x2, edgecolor='black', s=80); ax.grid(); ax.set_axisbelow(True); ax.set_xlim(-0.25,1.25); ax.set_ylim(-0.25,1.25) ax.set_xlabel('Pixel 2'); ax.set_ylabel('Pixel...
<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: Any one point inside the unit square would represent an image. For example the image associated with the point $(0.25,0.85)$ is shown below. Ste...
6,707
<ASSISTANT_TASK:> Python Code: raw_corpus = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", ...
<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: This is a particularly small example of a corpus for illustration purposes. Another example could be a list of all the plays written by Shakespe...
6,708
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import random import community import numpy as np import networkx as nx import matplotlib.pyplot as plt from tribe.utils import * from tribe.stats import * from operator import itemgetter ## Some Helper constants FIXTURES = os.path.join(os.getcwd(), "fixtures"...
<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 basics of creating a NetworkX Graph Step2: For testing and diagnostics it's useful to generate a random Graph. NetworkX comes with several ...
6,709
<ASSISTANT_TASK:> Python Code: # Load scored diffs and moderation event data d = load_diffs() df_block_events, df_blocked_user_text = load_block_events_and_users() df_warn_events, df_warned_user_text = load_warn_events_and_users() moderated_users = [('warned', df_warned_user_text), ('blocked', df_blo...
<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: The probability of being blocked after making a personal attack and increases as a function of how many times the user has been blocke...
6,710
<ASSISTANT_TASK:> Python Code: # BE SURE TO RUN THIS CELL BEFORE ANY OF THE OTHER CELLS import psycopg2 import pandas as pd import re # pull in our stopwords from nltk.corpus import stopwords stops = stopwords.words('english') # define our query statement = SELECT lower(t.text) as tweet, lower(h.text) as hashtag FROM...
<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: Our query this time is going to extract the both the hashtag and the tweets associated with the hashtag. We are going to created documents full ...
6,711
<ASSISTANT_TASK:> Python Code: %matplotlib inline import math import numpy as np from matplotlib import pyplot as plt from pyphysim.modulators.fundamental import BPSK, QAM, QPSK, Modulator from pyphysim.simulations import Result, SimulationResults, SimulationRunner from pyphysim.util.conversion import dB2Linear from py...
<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: Visualize the constellation Step2: Transmit though the channel Step3: Let's see the obtained error value. However, note that in order to get t...
6,712
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import os assert os.path.isfile('yearssn.dat') data=np.loadtxt('yearssn.dat') year = data[:,0] ssc = data[:,1] assert len(year)==315 assert year.dtype==np.dtype(float) assert len(ssc)==315 assert ssc.dtype==np.dtype(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: Line plot of sunspot data Step2: Use np.loadtxt to read the data into a NumPy array called data. Then create two new 1d NumPy arrays named year...
6,713
<ASSISTANT_TASK:> Python Code: N_members = 1254 N_respondents = 100 p = 0.6 N_yes = int(N_members*p) N_no = int(N_members*(1-p)) runs = 10000 # sufficient to get good statistics votes_samples = np.vstack(([ np.random.choice( np.hstack((np.ones(N_yes), np.zeros(N_no))), siz...
<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 simulate different voting outcomes Step2: With with 2 standard deviations (sigma) margin, we have 98% certainty (only looking at one ...
6,714
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris iris = load_iris() iris.keys() n_samples, n_features = iris.data.shape print(n_samples) print(n_features) # the sepal length, sepal width, petal length and petal width of the first sample (first flower) print(iris.data[0]) print(iris.data.shape) 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: The resulting dataset is a Bunch object Step2: The features of each sample flower are stored in the data attribute of the dataset Step3: The i...
6,715
<ASSISTANT_TASK:> Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf import strategy # Format price data. pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots. '''note: rcParams can't be in same cell as import matplotlib ...
<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: Some global data Step2: Run Strategy Step3: View logs Step4: Generate strategy stats - display all available stats Step5: Run Benchmark, Ret...
6,716
<ASSISTANT_TASK:> Python Code: new_data.crs = {'init':'epsg:4326'} new_data = new_data.to_crs("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ") new_data['newLon'] = new_data.apply(lambda c : c.geometry.x, axis=1) new_data['newLat'] = new_data.apply(...
<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: Uncomment to reproject Step2: The area is very big -> 35000 points. Step3: Residuals Step4: Residuals of $ Biomass ~ SppRich + Z(x,y) + \epsi...
6,717
<ASSISTANT_TASK:> Python Code: from pyspark.sql import SQLContext, Row sqlContext = SQLContext(sc) sqlContext from pyspark.sql import HiveContext, Row sqlContext= HiveContext(sc) sqlContext jsonfile = "file:///opt/spark-1.4.1-bin-hadoop2.6/examples/src/main/resources/people.json" df = sqlContext.read.load(jsonfile, 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: HiveContext, a superset of SQLContext, was recommended for most use cases. Please make sure you are using HiveContext now! Step2: Show time Ste...
6,718
<ASSISTANT_TASK:> Python Code: # read the data into a DataFrame import pandas as pd url = 'https://raw.githubusercontent.com/kjones8812/DAT4-students/master/kerry/Final/NBA_players_2015.csv' nba = pd.read_csv(url, index_col=0) nba.head() # examine the columns # examine the positions # map positions to numbers # create...
<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 2 Step2: Step 3 Step3: Step 4 Step4: Step 5 Step5: Bonus
6,719
<ASSISTANT_TASK:> Python Code: # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt import ipywidgets %matplotlib inline import os import sys ...
<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. 比特币 vs 黄金 ?莱特币 vs 白银 ? Step2: 接下来从内置期货symbol数据中查到国际期货黄金,白银的code: Step3: 将上述期货黄金,白银产品和比特币,莱特币一起做交易数据获取,如下: Step4: 只使用正负号相关度计算,如下所示: Step5: ...
6,720
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../src/') import opencourse as oc import numpy as np import scipy.stats as stt import matplotlib.pyplot as plt import pandas as pd from scipy import polyfit from scipy.ndimage.filters import gaussian_filter1d %matplotlib inline # Below we'll plot the PDF of a 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: Take and $\beta_0=3$ and $\beta_1=5$, then we can generate a dataset from our statistical model, such as the one pictured below. In black we plo...
6,721
<ASSISTANT_TASK:> Python Code: from SeisCL import SeisCL import numpy as np import matplotlib.pyplot as plt import os seis = SeisCL() help(seis.__init__) seis.ND = 2 # Number of dimension seis.N = np.array([250, 250]) # Grid size [NZ, NX, NY] seis.dh = dh = 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: SeisCL is controlled by a single class in python that will group all relevant information to perform forward and adjoint modeling. The class cre...
6,722
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() from pyquickhelper.ipythonhelper import open_html_form params = {"module":"", "version":"v..."} open_html_form(params, "fill the fields", "form1") form1 from pyquickhelper.ipythonhelper import open_html_form params= {"login...
<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: Form Step2: With a password Step3: To excecute an instruction when the button Ok is clicked Step4: Animated output Step5: In order to have a...
6,723
<ASSISTANT_TASK:> Python Code: import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World...
<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: Although this works, it is visually unappealing. We can improve on this using styles and themes. Step2: As our applications get more complicate...
6,724
<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: IMDBデータセットのダウンロード Step3: 結果として得られるマルチホットベクトルの1つを見てみましょう。単語のインデックスは頻度順にソートされています。このため、インデックスが0に近いほど1が多く出現するはずです。分布を見てみましょ...
6,725
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %datalab project set -p $PROJECT !pip install --upgrade ...
<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 idea is to look at the title of a newspaper article and figure out whether the article came from the New York Times or from TechCrunch. Ther...
6,726
<ASSISTANT_TASK:> Python Code: import sys try: sys.path.append('E:/Remote/chartpy') except: pass # support Quandl 3.x.x try: import quandl as Quandl except: # if import fails use Quandl 2.x.x import Quandl from chartpy import Chart, Style, Canvas # get your own free Quandl API key from https://www....
<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 need to download the data in order to plot. Let's use Quandl for this (although, I'd very much recommend using my library findatapy which pro...
6,727
<ASSISTANT_TASK:> Python Code: #@title Run to install MuJoCo and `dm_control` import distutils.util import subprocess if subprocess.run('nvidia-smi').returncode: raise RuntimeError( 'Cannot communicate with GPU. ' 'Make sure you are using a GPU Colab runtime. ' 'Go to the Runtime menu and select Cho...
<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 Step3: Model definition, compilation and rendering Step5: static_model is written in MuJoCo's XML-based MJCF modeling language. The fr...
6,728
<ASSISTANT_TASK:> Python Code: import pymks %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt from pymks.datasets import make_elastic_stress_random sample_size = 200 grain_size = [(15, 2), (2, 15), (7, 7), (8, 3), (3, 9), (2, 2)] n_samples = [sample_size] * 6 elas...
<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 Generation Step2: The array X contains the microstructure information and has the dimensions Step3: Lets take a look at the 6 types the ...
6,729
<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: Jupyter Step2: If the previous cell runs without producing any error messages, you are all set. Step3: A variable is a name that corresponds t...
6,730
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
<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: TFP Probabilistic Layers Step2: Make things Fast! Step3: Note Step4: Note that preprocess() above returns image, image rather than just image...
6,731
<ASSISTANT_TASK:> Python Code: vm_image_project='deeplearning-platform-release' vm_image_family='tf-ent-2-8-cu113-notebooks' machine_type='n1-standard-8' location='us-central1-a' accelerator_type='CHOOSE' # eg, 'NVIDIA_TESLA_V100' accelerator_cores=1 project='MY_PROJECT_ID' instance_name='MY_INSTANCE_NAME' print('Run 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: Step1: Remember that these machines are expensive, many hundreds of dollars a month. So make sure you stop the VM when you are not using it, either at ...
6,732
<ASSISTANT_TASK:> Python Code: import pandas as pd json_file = 'sample_data' list(pd.read_json(json_file, lines=True)) import csv import json from nltk.tokenize import TweetTokenizer from tqdm import tqdm MIN_NUM_WORD_TOKENS = 10 TOTAL_NUM_LINES = 53851542 # $ wc -l data_full.json PBAR_UPDATE_SIZE = 10000 tokenizer ...
<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: Transform the full JSON file into a CSV, removing any stuff that we won't need Step3: Creates CSVs of text from comments made by users who have...
6,733
<ASSISTANT_TASK:> Python Code: !pip install hanlp_restful from hanlp_restful import HanLPClient HanLP = HanLPClient('https://www.hanlp.com/api', auth=None, language='zh') # auth不填则匿名,zh中文,mul多语种 doc = HanLP.parse("2021年HanLPv2.1为生产环境带来次世代最先进的多语种NLP技术。阿婆主来到北京立方庭参观自然语义科技公司。") print(doc) doc.pretty_print() !pip instal...
<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: 调用parse接口,传入一篇文章,得到HanLP精准的分析结果。 Step3: 可视化 Step4: 申请秘钥 Step5: 加载模型 Step6: 调用hanlp.load进行加载,模型会自动下载到本地缓存。自然语言处理分为许多任务...
6,734
<ASSISTANT_TASK:> Python Code: np.random.seed(10) p, q = (np.random.rand(i, 2) for i in (4, 5)) p_big, q_big = (np.random.rand(i, 80) for i in (100, 120)) print(p, "\n\n", q) def naive(p, q): ''' fill your code in here... ''' rows, cols = np.indices((p.shape[0], q.shape[0])) print(rows, end='\n\n') print(cols...
<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: Solution Step2: Use matching indices Step3: Use a library Step4: Numpy Magic Step5: Compare methods
6,735
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf with open('reviews.txt', 'r') as f: reviews = f.read() with open('labels.txt', 'r') as f: labels = f.read() reviews[:2000] from string import punctuation all_text = ''.join([c for c in reviews if c not in punctuation]) reviews = all_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: Data preprocessing Step2: Encoding the words Step3: Encoding the labels Step4: Okay, a couple issues here. We seem to have one review with ze...
6,736
<ASSISTANT_TASK:> Python Code: !git rev-parse HEAD from copy import deepcopy from datetime import timedelta from itertools import product import logging from math import floor, ceil, log10 import pickle from random import sample, seed, shuffle from time import time import numpy as np import pandas as pd from tqdm 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: Benchmark Step2: Implement Levenshtein term similarity matrix Step3: Director class benchmark Step4: The following tables show how long it ta...
6,737
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (0, 10) DON'T MODIFY AN...
<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: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
6,738
<ASSISTANT_TASK:> Python Code: from yahoo_finance import Share import numpy as np #for this Example I will use google's finances #create an instance of Share google = Share('GOOG') #now that an instance of Share is created (google), we will call its functions to get the prices #date and time of the trade date = googl...
<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 need to create an instance of Share. Using that instance we will get prices, volumes, ratios and all other company information Step2: ...
6,739
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import PyAstronomy.pyasl as pyasl import eniric from eniric import config from eniric.broaden import rotational_convolution, resolution_convolution from eniric.utilities import band_limits, load_aces_spectrum, wav_selector from scripts.ph...
<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 Step2: Timing Convolutions Step3: The rotational convolution in eniric is ~10x faster than Step4: Resolution convolution is around ...
6,740
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns import keras import h5py import time from matplotlib import gridspec datadir = "" mean_and_std = np.load(datadir + 'mean_and_std.npy') mean_labels = mean_and_std[0] std_labels = mean_and_std[1] num_labels = mean_and...
<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: Obtain data for normalizing labels and define function to denormalize labels** Step2: Define functions to obtain test data Step3: Load test da...
6,741
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.image as mpimg from matplotlib import rcParams import seaborn as sb %matplotlib inline rcParams['figure.figsize'] = 5, 4 ...
<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 up inline matplotlib Step2: Import Game Modules From a Given Path Step3: Setting Up Game Parameters Step4: seed PRNG Step5: Set up the s...
6,742
<ASSISTANT_TASK:> Python Code: import pandas as pd porsche = pd.read_csv("PorschePrice.csv") porsche.shape porsche.head(5) porsche = porsche.rename(columns = {'Unnamed: 0':'Number'}) porsche.head(5) porsche.describe() import seaborn as sns import matplotlib.pyplot as plt sns.pairplot(porsche[["Price", "Age", "Mileag...
<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: Explore the Dataset Step2: Plotting Using Seaborn and PyPlot Step3: Pairplot Step4: Radial Visualization Step5: Vertical Barchart Step6: Ho...
6,743
<ASSISTANT_TASK:> Python Code: import os from datetime import timedelta import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, ve...
<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: ~mne.Annotations in MNE-Python are a way of storing short strings of Step2: Notice that orig_time is None, because we haven't specified it. In ...
6,744
<ASSISTANT_TASK:> Python Code: from spirack import SPI_rack, B2b_module, D5a_module, D4b_module import logging from time import sleep from tqdm import tqdm_notebook import numpy as np from scipy import signal from plotly.offline import init_notebook_mode, iplot, plot import plotly.graph_objs as go init_notebook_mode(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: Open the SPI rack connection and unlock the controller. This is necessary after bootup of the controller module. If not unlocked, no communicati...
6,745
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS from IPython.display import display from ipywidgets import * from mpl_toolkits.mplot3d import Axes3D import plotBL HTML('../style/code_to...
<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 section specific modules Step2: 4.5.2 $uv$ coverage Step3: From the list above, you can select different configurations corresponding ...
6,746
<ASSISTANT_TASK:> Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sam...
<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: Loading continuous data Step2: As you can see above, Step3: By default, the Step4: Querying the Raw object Step5: <div class="alert alert-...
6,747
<ASSISTANT_TASK:> Python Code: reset_start_time(O.just) stream = O.just({'answer': rand()}) disposable = subs(stream) sleep(0.5) disposable = subs(stream) # same answer # all stream ops work, its a real stream: disposable = subs(stream.map(lambda x: x.get('answer', 0) * 2)) print('There is a little API difference to 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: ..that was returned from a function called at subscribe-time Step2: ..that was returned from an Action, Callable, Runnable, or something of tha...
6,748
<ASSISTANT_TASK:> Python Code: import this import requests url = 'https://github.com/lamenezes/python-intro' # não é necessário declarar variáveis em python response = requests.get(url) # e nem especificar seu tipo response.status_code print(response.headers) dict(response.headers) response.headers['content-type...
<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: Agora é hora de por as mãos na massa! Vamos do começo Step2: Agora vamos fazer uma requisição HTTP ao Github para baixar o conteúdo do repositó...
6,749
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
<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: Variational Inference on Probabilistic Graphical Models with Joint Distributions Step2: The regression model is specified as follows Step3: Ex...
6,750
<ASSISTANT_TASK:> Python Code: # Выполним инициализацию основных используемых модулей %matplotlib inline import random import matplotlib.pyplot as plt from sklearn.preprocessing import normalize import numpy as np with open('winequality-red.csv') as f: f.readline() # пропуск заголовочной строки data = np.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: Выполним загрузку данных Step2: В качестве альтернативного варианта, можно выполнить загрузку данных напрямую из репозитория UCI, воспользовавш...
6,751
<ASSISTANT_TASK:> Python Code: # Load Biospytial modules and etc. %matplotlib inline import sys sys.path.append('/apps') sys.path.append('..') sys.path.append('../spystats') import django django.setup() import pandas as pd import matplotlib.pyplot as plt import numpy as np ## Use the ggplot style plt.style.use('ggplot'...
<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 this to automate the process. Be carefull it can overwrite current results Step2: Now we will obtain the data from the calculated empirical...
6,752
<ASSISTANT_TASK:> Python Code: from proxy.http.parser import HttpParser, httpParserTypes from proxy.http import httpMethods from proxy.common.utils import HTTP_1_1 request = HttpParser(httpParserTypes.REQUEST_PARSER) request.path, request.method, request.version = b'/', httpMethods.GET, HTTP_1_1 request.add_header(b'Ho...
<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: But, this is a painful way to construct request packets. Hence, other high level abstractions are available. Step2: build_http_request ensures...
6,753
<ASSISTANT_TASK:> Python Code: %%bash export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT !pip install tensorflow==2.1.0 --user import os, json, math import numpy as np import shutil import logging # SET TF ERROR LOG VERBOSITY logging.getLogger(...
<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...
6,754
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import numpy as np import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline from datetime import date date.today() author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises" tf.__version__ np.__version__ _x = np.linspace(...
<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: Activation Functions Step2: Q2. Apply sigmoid and tanh to x. Step3: Q3. Apply softmax to x. Step4: Q4. Apply dropout with keep_prob=.5 to x. ...
6,755
<ASSISTANT_TASK:> Python Code: %load_ext sql %sql mysql://steinam:steinam@localhost/versicherung_complete % load_ext sql %%sql select Personalnummer, Name, Vorname from Mitarbeiter where Abteilung_ID = ( select ID from Abteilung where Kuerzel = 'Schadensabwicklung' ); %%sql select Personalnummer, Name, Vorn...
<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: Vertreter für Wert Step3: Lösung Step4: Vertreter für Spaltenfunktionen Step5: Aufgabe Step6: Bemerkung Step7: Aufgabe Step8: Ver...
6,756
<ASSISTANT_TASK:> Python Code: import folium from folium import plugins m = folium.Map([45, 3], zoom_start=4) plugins.ScrollZoomToggler().add_to(m) m import numpy as np N = 100 data = np.array( [ np.random.uniform(low=35, high=60, size=N), # Random latitudes in Europe. np.random.uniform(low=-12, 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: MarkerCluster Step2: Terminator Step3: BoatMarker Step4: BeautifyIcon Step5: Fullscreen Step7: Timestamped GeoJSON Step8: FeatureGroupSubG...
6,757
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Seaborn is a Python data visualization library based on matplotlib. %matplotlib inline df_USAhousing = pd.read_csv('../USA_Housing_toy.csv') # Show the first five row. df_USAhous...
<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 Dataset Step2: Let's check for any null values. Step3: Let's take a peek at the first and last five rows of the data for all columns....
6,758
<ASSISTANT_TASK:> Python Code: import sys import os import ee # This script assumes your authentification credentials are stored as operatoring system # environment variables. __MY_SERVICE_ACCOUNT = os.environ.get('MY_SERVICE_ACCOUNT') __MY_PRIVATE_KEY_FILE = os.environ.get('MY_PRIVATE_KEY_FILE') # Initialize the Earth...
<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 Crisis Mapping Toolkit Step2: Load a domain Step3: Display the domain Step4: A GUI should appear in a seperate window displaying the...
6,759
<ASSISTANT_TASK:> Python Code: print(2) print("is even.") print(2, "is even.") print(1, 2, 3) print(1, 2, 3, sep='|') print(1) print(2) print(3) print(1, end=' ') print(2, end=' ') print(3, end=' ') print('%d is odd, %d is even' % (3, 4)) print('Hello %s!' % 'Pesho') <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: Step1: Можем да променим разделителя като добавим аргумент sep='&lt;&lt;разделител&gt;&gt;'. Step2: По подразбиране print поставя символ за край на ре...
6,760
<ASSISTANT_TASK:> Python Code: import time import sys import os from PIL import Image from pyDrivers.ada_lcd import * import pyDrivers.ILI9341 as TFT import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI myGPIO = GPIO.get_platform_gpio() myGPIO.setup(12,GPIO.IN) myGPIO.setup(16,GPIO.IN) lcd = ADA_LCD() lcd.clea...
<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'll start by invoking the GPIO class, which will identify our board and initialize the pins. We will use two pins for input for scrolling ...
6,761
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np tf.__version__ from mnist import MNIST data = MNIST(data_dir="data/MNIST/") print("Size of:") print("- Training-set:\t\t{}".format(data.num_train)) print("- Validation-set:\t{}".format(data.nu...
<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: This was developed using Python 3.6 (Anaconda) and TensorFlow version Step2: Load Data Step3: The MNIST data-set has now been loaded and consi...
6,762
<ASSISTANT_TASK:> Python Code: from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.layers.normalization import BatchNormalization from keras.layers.advanced_activations import PReLU from keras...
<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: Simple neural network with a couple of dense layers. The hidden_sizes list defines the hidden layers, in this case 2 hid...
6,763
<ASSISTANT_TASK:> Python Code: from IPython.display import display import spot spot.setup(show_default='.bas') spot.automaton(''' HOA: v1 States: 2 Start: 0&1 AP: 2 "a" "b" acc-name: Buchi Acceptance: 1 Inf(0) --BODY-- State: 0 [0] 0 [!0] 1 State: 1 [1] 1 {0} --END-- ''') spot.automaton(''' HOA: v1 States: 2 Start: 0&...
<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: universal edges are handled as if they were many distinct existencial edges from the point of view of scc_info, so the acceptance / rejection st...
6,764
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from matplotlib import pyplot %matplotlib inline titanic = pd.read_csv("train.csv") titanic_test = pd.read_csv("test.csv") titanic.shape titanic.describe() titanic.info() titanic.head(3) titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median()...
<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: Training Step2: The most common embarkation port is S, so let's assume everyone got on there. Step3: From the Kaggle competition description, ...
6,765
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import numpy as np import mne from mne.datasets import sample from mne.beamformer import lcmv print(__doc__) data_path = sample.data_path() raw_fname = data_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: Get epochs
6,766
<ASSISTANT_TASK:> Python Code: # Segunda parte: Aplicaciones en Python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import time from PIL import Image ##Aquí abro la imagen y la convierto a gris im = Image.open("/Users/usuario/Documents/MaestriaCD/Propedeutico/PropedeuticoDataScience2017/Tarea/...
<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: Se mostrará una aplicación de la SVD a la compresión de imágenes y reducción de ruido. Step2: Pregunta Step3: Hacer una función que me resuelv...
6,767
<ASSISTANT_TASK:> Python Code: # coding: utf-8 import pickle from pprint import pformat import numpy as np np.set_printoptions(precision=4) np.set_printoptions(edgeitems=1) with open("report.pkl", 'r') as pfile: report = pickle.load(pfile) print("Unconstraint") print("-" * 10) print(" - total of {0} studies".form...
<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 report Step2: Inspect the report on all the floatting parameters Step3: Inspect the report on a subset of the floatting parameters St...
6,768
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd from os.path import join from pylab import rcParams import matplotlib.pyplot as plt rcParams['figure.figsize'] = (13, 6) plt.style.use('ggplot') #import nilmtk from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore from ni...
<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: Show versions for any diagnostics Step2: Load dataset Step3: Period of interest 4 days during normal week Step4: Training Step5: Set two day...
6,769
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from scipy.optimize import minimize from sklearn.preprocessing import StandardScaler def sig1(z): # sigma return(1/(1+np.exp(-z))) def sig2(z): # sigma'(z) phat = sig1(z) return(phat*(1-phat)) class y2ord(): # Convert ordinal to 1, 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: Univariate example Step2: A confusion martrix shows that the predited level $\tilde y$ aligns closely with the true label. Furthermore, there i...
6,770
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<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: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ...
6,771
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn import cross_validation from sklearn.cross_validation import KFold from sklearn.cross_validation import train_test_split from skle...
<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.0 - Feature Generation Step2: 3.0 - Generate plots of each feature Step3: 4.0 - Train model using RandomForestClassifier Step4: 5.0 - Predi...
6,772
<ASSISTANT_TASK:> Python Code: import bioframe import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import pearsonr, spearmanr base_dir = '/tmp/bioframe_tutorial_data/' assembly = 'GRCh38' ctcf_peaks = bioframe.read_table("https://www.encodeproject.org/files/ENCFF401MQL/@@download/E...
<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 CTCF ChIP-seq peaks for HFF from ENCODE Step2: Get CTCF motifs from JASPAR Step3: Overlap peaks & motifs Step4: There are often multiple...
6,773
<ASSISTANT_TASK:> Python Code: from _keys.facebook import USER_ID, ACCESS_TOKEN, paging_token import requests host = 'https://graph.facebook.com/v2.8' u = '{}/{}/posts?access_token={}'.format(host, USER_ID, ACCESS_TOKEN) data1 = requests.get(u).json() pg2 = '{}/{}/posts?limit=25&until=1486832400&__paging_token={}&acces...
<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 JSON data is saved into the variable data,which is a list of dictionaries, so we can now use the data structure functions to access informat...
6,774
<ASSISTANT_TASK:> Python Code: # How to compute intercept range given an angle range import numpy as np angle_range_degrees = np.array([15.0, 35.0]) angle_range = angle_range_degrees * np.pi / 180 print np.cos(angle_range) import nengo model = nengo.Network() with model: ens = nengo.Ensemble(n_neurons=400, dimensi...
<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: So, in order to have tuning curves lke that, we want to have neurons with intercepts=nengo.dists.Uniform(0.82, 0.97) which is close enough to wh...
6,775
<ASSISTANT_TASK:> Python Code: import numpy as np import seaborn as sns import scipy.stats as stats %matplotlib inline def lcg(n, m=2**31-1, a=16807, c=0, seed=2**30): x = np.zeros(n+1) x[0]=seed for i in range(1,n+1): x[i] = (a * x[i-1]+c)%m return x[1:]/m lcg(10, m=31, a=13, c=0, seed=3) 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: Step1: 2. Generador congruencial lineal Step2: Ejemplo Step3: Generador mínimo estándar Step4: Generado Randu (Usado por IBM) Step5: 3. Método de B...
6,776
<ASSISTANT_TASK:> Python Code: from IPython.display import Image # Add your filename and uncomment the following line: Image(filename='graph2.JPG') <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: Step1: Violations of graphical excellence and integrity
6,777
<ASSISTANT_TASK:> Python Code: import geopandas geopandas.tools.geocode('2900 boulevard Edouard Montpetit, Montreal', provider='nominatim', user_agent="mon-application") <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: Step1: Géocodage
6,778
<ASSISTANT_TASK:> Python Code: !pip install --pre deepchem import deepchem as dc dc.__version__ tasks, datasets, transformers = dc.molnet.load_tox21(featurizer='ECFP') train_dataset, valid_dataset, test_dataset = datasets print(train_dataset) train_dataset.w model = dc.models.MultitaskClassifier(n_tasks=12, n_featu...
<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 now import the deepchem package to play with. Step2: What is a Fingerprint? Step3: The feature array X has shape (6264, 1024). That me...
6,779
<ASSISTANT_TASK:> Python Code: from geo.models import SampleLocation from database.models import Site from shapely.geometry import shape, MultiPoint import geopandas import pandas import numpy from django.db import connection def get_geodataframe(queryset, modification=None, crs={'+init':'epsg:31254'}): query = qu...
<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: function declarations Step2: load locations from database Step3: loop through locations and compute distance Step4: compute the distance mean...
6,780
<ASSISTANT_TASK:> Python Code: class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), -1) def __str__(self): return 'Flatten()' model = nn.Sequential(OrderedDict([ ('conv2d_1', nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3)), ('relu_1', nn.ReLU()), ('...
<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: Accessing the layers Step2: Moreover .modules and .children provide generators for accessing layers. Step3: Getting the weigths. Step4: Getti...
6,781
<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: 모든 Cloud TPU는 bfloat16을 지원합니다. Step4: 이 정책은 레이어의 두 가지 중요한 측면, 즉 레이어 계산이 수행되는 dtype과 레이어 변수의 dtype을 지정합니다. 위에서 ...
6,782
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() def polynome ( x ) : x2 = x*x return x2 + x - 5 def polynome ( x, coefficient ) : return sum ( [ x**i * c for i,c in enumerate(coefficient) ] ) y = polynome ( 1.2, [ 1, 2, -1] ) # calcul de -x^2 + 2x + 1 pour ...
<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: Fonctions Step2: Une fonction commence toujours par def. Entre parenthèses, ce sont les paramètres (ou entrées de la fonction). Ce qui suit le ...
6,783
<ASSISTANT_TASK:> Python Code: # import the dataset from quantopian.interactive.data.eventvestor import issue_debt # or if you want to import the free dataset, use: # from quantopian.interactive.data.eventvestor import issue_debt_free # import data operations from odo import odo # import other libraries we will use 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: Let's go over the columns Step2: Now suppose we want a DataFrame of the Blaze Data Object above, want to filter it further down to the announce...
6,784
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import os import PIL tf.__version__ # Obtain data from url:"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip" zip_file = tf.keras.utils.get_file(origin="https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip", ...
<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 keras, input could be ndarray, or generator. We could just use model.predict(test_generator). But to simplify, here we just input the first r...
6,785
<ASSISTANT_TASK:> Python Code: samples_per_symbol = 64 # this is so high to make stuff plottable symbols = [1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0] data = [] for x in symbols: data.extend([1 if x else -1] * samples_per_symbol) plt.plot(data) plt.title('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: Modulation Step2: Spectogram shows that we have synthesized positive frequency for True bit and negative for False.
6,786
<ASSISTANT_TASK:> Python Code: import mbuild as mb class MonoLJ(mb.Compound): def __init__(self): super(MonoLJ, self).__init__() lj_particle1 = mb.Particle(name='LJ', pos=[0, 0, 0]) self.add(lj_particle1) lj_particle2 = mb.Particle(name='LJ', pos=[1, 0, 0]) self.add(lj_partic...
<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: While this would work for defining a single molecule or very small system, this would not be efficient for large systems. Instead, the clone an...
6,787
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image(url='http://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg/251px-The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_...
<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. How would you estimate the time it takes for a photon to travel from the core to the surface? Step2: This is a 3D random walk (if you take A...
6,788
<ASSISTANT_TASK:> Python Code: def double(x): return(2*x); print double(1); print double(2); print double(3); def print_double(x): print(2*x); print_double(1); print_double(2); print_double(3); def leet(): return 1337; #Try what "print leet()" does. #Enter your code here: #Write your function here #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: Look at some sample outputs below Step2: We can define a function in python by the def keyword, followed by the name of the function, a set of ...
6,789
<ASSISTANT_TASK:> Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1) # Loading the data (sig...
<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: Run the next cell to load the "SIGNS" dataset you are going to use. Step2: As a reminder, the SIGNS dataset is a collection of 6 signs represen...
6,790
<ASSISTANT_TASK:> Python Code: from noodles import run_single from noodles.tutorial import (add, sub, mul) u = add(5, 4) v = sub(u, 3) w = sub(u, 2) x = mul(v, w) answer = run_single(x) print("The answer is {0}.".format(answer)) import urllib.request import json import re class Translate: Translate words and sente...
<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: That looks like any other Python code! But this example is a bit silly. Step3: We start with a list of strings that desparately need translatio...
6,791
<ASSISTANT_TASK:> Python Code: class Pen(): def __init__(self, size, name): self.name = name self.size = size def set_name(self, name): self.name = name class BallPen(Pen): def __init__(self, size, name, color): self.color = color super().__init__(size, 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: BallPen & InkPen both are initializing the parent class using super().__init(size, name) function. Now lets create few objects of both, Step2: ...
6,792
<ASSISTANT_TASK:> Python Code: N = 10 theta = 0.6 rv = sp.stats.binom(N, theta) rv xx = np.arange(N + 1) plt.bar(xx, rv.pmf(xx), align="center") plt.ylabel("P(x)") plt.title("pmf of binomial distribution") plt.show() np.random.seed(0) x = rv.rvs(100) x sns.countplot(x) plt.show() y = np.bincount(x, minlength=N) / le...
<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: pmf 메서드를 사용하면 확률 질량 함수(pmf Step2: 시뮬레이션을 하려면 rvs 메서드를 사용한다. Step3: 이론적인 확률 분포와 샘플의 확률 분포를 동시에 나타내려면 다음과 같은 코드를 사용한다.
6,793
<ASSISTANT_TASK:> Python Code: % matplotlib inline from __future__ import print_function import os.path from collections import Counter import numpy as np import pandas as pd import matplotlib.pyplot as plt from enrich2.variant import WILD_TYPE_VARIANT import enrich2.plots as enrich_plot pd.set_option("display.max_rows...
<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: Modify the results_path variable in the next cell to match the output directory of your Enrich2-Example dataset. Step2: Open the Experiment HDF...
6,794
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[5] plt.imshow(img.reshape((28, 28)), cmap='...
<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: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits. Step2: We'll train an autoe...
6,795
<ASSISTANT_TASK:> Python Code: import re numbers = re.compile('(\d+)') UPPER_LIMIT = 4294967295 with open('../inputs/day20.txt', 'r') as f: data = [ tuple(map( int, numbers.findall(line))) for line in f.readlines()] data.sort() rule_index = 0 n = 0 while n <= UPPER_LIMIT: 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: Part Two
6,796
<ASSISTANT_TASK:> Python Code: # Import some stuff import numpy as np import pandas as pd import scipy.spatial.distance as spd from pymer4.simulate import easy_multivariate_normal from pymer4.models import Lm import matplotlib.pyplot as plt % matplotlib inline # Prep some data X = easy_multivariate_normal(50,2,corrs=....
<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: Inner product Step2: Covariance Step3: Cosine Similarity Step4: Pearson Correlation Step5: OLS (univariate w/o intercept) Step6: OLS (univa...
6,797
<ASSISTANT_TASK:> Python Code: # A comma-delimited list of the words you want to train for. # The options are: yes,no,up,down,left,right,on,off,stop,go # All the other words will be used to train an "unknown" label and silent # audio data with no spoken words will be used to train a "silence" label. WANTED_WORDS = "yes...
<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: DO NOT MODIFY the following constants as they include filepaths used in this notebook and data that is shared during training and inference. Ste...
6,798
<ASSISTANT_TASK:> Python Code: 2 + 3 2*3 2**3 sin(pi) from math import sin, pi sin(pi) a = 10 a c = from pruebas_1 import prueba_1_1 prueba_1_1(_, c) A = [2, 4, 8, 10] A A*2 f = lambda x: x**2 + 1 f(2) def g(x): y = x**2 + 1 return y g(2) def cel_a_faren(grados_cel): grados_faren = # Escrib...
<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: Sin embargo no existen funciones trigonométricas cargadas por default. Para esto tenemos que importarlas de la libreria math Step2: Variables S...
6,799
<ASSISTANT_TASK:> Python Code: import graphlab sales = graphlab.SFrame('kc_house_data.gl/') from math import log, sqrt sales['sqft_living_sqrt'] = sales['sqft_living'].apply(sqrt) sales['sqft_lot_sqrt'] = sales['sqft_lot'].apply(sqrt) sales['bedrooms_square'] = sales['bedrooms']*sales['bedrooms'] # In the dataset, '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: Load in house sales data Step2: Create new features Step3: Squaring bedrooms will increase the separation between not many bedrooms (e.g. 1) a...