Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
12,700
<ASSISTANT_TASK:> Python Code: import os with open(os.path.join("datasets", "smsspam", "SMSSpamCollection")) as f: lines = [line.strip().split("\t") for line in f.readlines()] text = [x[1] for x in lines] y = [x[0] == "ham" for x in lines] from sklearn.model_selection import train_test_split text_train, text_test, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Previously, we applied the feature extraction manually, like so Step2: The situation where we learn a transformation and then apply it to the t...
12,701
<ASSISTANT_TASK:> Python Code: %gui qt import vtk from vtkviewer import SimpleVtkViewer #help(vtk.vtkRectilinearGridReader()) # do not forget to call "Update()" at the end of the reader rectGridReader = vtk.vtkRectilinearGridReader() rectGridReader.SetFileName("data/jet4_0.500.vtk") rectGridReader.Update() rectGridOu...
<SYSTEM_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. Data input (source) Step2: 2. Filters Step3: 3. Mappers Step4: 4. Actors Step5: 5. Renderers and Windows
12,702
<ASSISTANT_TASK:> Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Generate plots inline %pylab inline import json import os # Support to initialise and configure your test environment import devlib from env import TestEnv # Support to configure and run RTApp based workloads from wlgen 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: Test environment setup Step2: Workload configuration Step3: The output of the previous cell reports the main properties of the generated Step4...
12,703
<ASSISTANT_TASK:> Python Code: from bs4 import BeautifulSoup import requests import pandas as pd from pandas import Series,DataFrame url = 'http://www.ucop.edu/operating-budget/budgets-and-reports/legislative-reports/2013-14-legislative-session.html' # Request content from web page result = requests.get(url) c = resu...
<SYSTEM_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 our quick web scraping tutorial, we'll look at some legislative reports from the University of California Web Page. Feel free to experiment ...
12,704
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.1,<2.2" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b.add_dataset('lc', times=np.linspace(0,1,6)) b.add_dataset('mesh') print b['times@mes...
<SYSTEM_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 always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: The 'Mesh' Dataset Step3:...
12,705
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import numpy as np import math import timeit import matplotlib.pyplot as plt %matplotlib inline from cs231n.data_utils import load_CIFAR10 def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=10000): Load the CIFAR-10 dataset from disk 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: What's this TensorFlow business? Step2: Example Model Step3: TensorFlow supports many other layer types, loss functions, and optimizers - you ...
12,706
<ASSISTANT_TASK:> Python Code: from collections import defaultdict, Counter from itertools import zip_longest import json import os import re import sys import urllib import numpy as np import requests from consequence_prediction.vep_mapping_pipeline.consequence_mapping import * from eva_cttv_pipeline.clinvar_xml_io.cl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Phenotypes Step2: Summary for phenotypes Step3: Precise Step7: Uncertainty from spans Step9: Uncertainty from genes
12,707
<ASSISTANT_TASK:> Python Code: import pandas as pd data = pd.read_csv("../data/iris.data") # convert to NumPy arrays because they are the easiest to handle in sklearn variables = data.drop(["class"], axis=1).as_matrix() classes = data[["class"]].as_matrix().reshape(-1) # import cross-validation scorer and KNeighborsCla...
<SYSTEM_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
12,708
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-3', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
12,709
<ASSISTANT_TASK:> Python Code: import geosoft.gxpy.gx as gx import geosoft.gxpy.utility as gxu gxc = gx.GXpy() url = 'https://github.com/GeosoftInc/gxpy/raw/9.3/examples/tutorial/Geosoft%20modules%20-%20gxapi%20and%20gxpy/' gxu.url_retrieve(url + 'test.grd') gxu.url_retrieve(url + 'test.grd.gi') gxc = None import geos...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: GX API (geosoft.gxapi) Step2: GXPY (geosoft.gxpy) Step3: You will find that many gxpy classes map closely to underlying gxapi classes, but wit...
12,710
<ASSISTANT_TASK:> Python Code: # Imports and directives %matplotlib inline import numpy as np from math import log import matplotlib.pyplot as plt from matplotlib.mlab import PCA as mlabPCA import javalang import os, re, requests, zipfile, json, operator from collections import Counter import colorsys import random fro...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Analyzing one project Step2: 1. Commit frequency Step3: 2. Distinct committers Step4: 3. Class reference count Step5: 4. Inheritance count S...
12,711
<ASSISTANT_TASK:> Python Code: workDir = '../../t/SIPSim_example/' nprocs = 3 import os # Note: you will need to install `rpy2.ipython` and the necessary R packages (see next cell) %load_ext rpy2.ipython %%R library(ggplot2) library(dplyr) library(tidyr) workDir = os.path.abspath(workDir) if not os.path.isdir(workDir)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Init Step2: Experimental design Step3: Pre-fractionation communities Step4: Note Step6: Simulating fragments Step7: Simulation Step8: Plot...
12,712
<ASSISTANT_TASK:> Python Code: import pandas as pd from pandas import * import matplotlib.pyplot as plt %matplotlib inline from ggplot import * from numpy import random plt.style.use('ggplot') data = pd.read_csv("../Data/Histogram/pared_down.csv") data data.columns table = pivot_table(data, index=['Tree'], columns=[...
<SYSTEM_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 data using pandas. Step2: Pivot the table to group the data by tree. Step3: Plot using native pandas plotting.
12,713
<ASSISTANT_TASK:> Python Code: def quad_func (x): return 5 * x ** 2 -23 * x + 47 # Training Set + Eval Set: 200 samples (70%, 30% split) # Test Set: 60 samples # Total: 260 samples np.random.seed(5) samples = 260 x_vals = pd.Series(np.random.rand(samples) * 20) x2_vals = x_vals ** 2 y_vals = x_vals.map(quad_func) y...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h4>Training and Evaluation Set</h4> Step2: Test 1 Step3: Test 1
12,714
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.spatial import scipy.optimize points1 = np.array([(x, y) for x in np.linspace(-1,1,7) for y in np.linspace(-1,1,7)]) N = points1.shape[0] points2 = 2*np.random.rand(N,2)-1 C = scipy.spatial.distance.cdist(points1, points2, metric='minkowski', p=1) _, result...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
12,715
<ASSISTANT_TASK:> Python Code: from IPython.display import Image, display Image('images/08_transfer_learning_flowchart.png') %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import time from datetime import timedelta import os # Functions and classes for loading and using 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: Imports Step2: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version Step3: Load Data for CIFAR-10 Step4: The data dimensio...
12,716
<ASSISTANT_TASK:> Python Code: %matplotlib inline import eland as el import numpy as np ES_URL = 'http://localhost:9200/' df = el.read_es(ES_URL, 'ecs-search-metrics') df.dtypes print(df.info_es()) df.head() df['SearchMetrics.click.result.rank'].describe() df['SearchMetrics.click.result.rank'].hist() df['source.user...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Loading and Preparation Step2: What is the distribution of ranks of results clicked on? Step3: How many users are in the dataset? Step4: ...
12,717
<ASSISTANT_TASK:> Python Code: %run 'ipython_startup.py' import seaborn as sns dspr = pd.read_csv(os.path.join(PROJ, 'analysis_output/mmc/dsrp_sex_det_genes_for_mmc.csv'), index_col='_NAME_') cegs = pd.read_csv(os.path.join(PROJ, 'analysis_output/mmc/cegsV_sex_det_gene_for_mmc.csv'), index_col='_NAME_') dspr.drop('Rm6...
<SYSTEM_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 Data Step2: Variation among genes in sex hierarchy Step3: Correlation
12,718
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'mri-agcm3-2', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
12,719
<ASSISTANT_TASK:> Python Code: birthdays = dict() print( birthdays ) birthdays['0704'] = 'Steve' birthdays['0529'] = 'Tony' print( birthdays ) print( birthdays['0529'] ) # Get the number of key-value pairs print( len( birthdays ) ) # Get the values in the dictionary print( birthdays.values() ) # Get the keys in 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: To add an item to the dictionary, use square brackets like a list Step2: Note that order isn't preserved in a dictionary (unlike a list) Step3:...
12,720
<ASSISTANT_TASK:> Python Code: %matplotlib inline from collections import defaultdict import json import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd from matplotlib import rcParams import matplotlib.cm as cm import matplotlib as mpl #colorbrewer2 Dark2 qualitative color table dark...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: HW4 Step2: Description of the data set Step3: The data frame is a frame of reviews. We have joined in information about users and businesses i...
12,721
<ASSISTANT_TASK:> Python Code: # Data path/filename t_ind = 38 data_path = '../data/' file_name = data_path + 'data_sim_low.hdf5' data_options = {'flag_cell': True, 'flag_electode': False} data = data_in(file_name, **data_options) localization_options = {'p_vres':20, 'p_jlen':0, 'p_erad': 5, 't_ind': 38, 'flag_depthwe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: And chose the localization parameters. You can check the parameters necessary in the documentation. Step2: You can see the different functions ...
12,722
<ASSISTANT_TASK:> Python Code: #!pip install --user miepython import numpy as np import matplotlib.pyplot as plt try: import miepython except ModuleNotFoundError: print('miepython not installed. To install, uncomment and run the cell above.') print('Once installation is successful, rerun this cell again.') ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: Goals for this notebook Step5: Mie scattering describes the special case of the interaction of light passing through a non-absorbing medium wit...
12,723
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline from keras.applications import vgg16 from keras.layers import Input from dream import * from scipy.misc import imread img_dir = '../images/dream/sky1024px.jpg' I = imread(img_dir) plt.imshow(I) plt.axis('off') plt.show() settings = {'...
<SYSTEM_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 will use the same image for the example. Step2: Here are the settings we will use, including the layers of the network we want to "dream" an...
12,724
<ASSISTANT_TASK:> Python Code: % matplotlib inline from __future__ import division import os import nibabel as nib import numpy as np from neuropower import peakdistribution import scipy.integrate as integrate import pandas as pd import matplotlib.pyplot as plt import palettable.colorbrewer as cb if not 'FSLDIR' in os....
<SYSTEM_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. What is the voxelwise threshold? Step2: 2. Definition of alternative Step3: 3. How large statistic in a field be to exceed the threshold wi...
12,725
<ASSISTANT_TASK:> Python Code: # Import modules needed to reproduce results import os import plotnine from plotnine import * import pandas as pd from scipy import stats import numpy as np from statsmodels.stats.proportion import proportion_confint as prop_CI def tdist_2dist(mu1, mu2, se1, se2, n1, n2, var_eq=False): ...
<SYSTEM_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 a rule, I always conduct statistical simulations to make sure the functions I have written actually perform the way I expect them to when the...
12,726
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scikit-learn,nltk # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py import pyprind import pandas as pd 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: <br> Step2: Shuffling the DataFrame Step3: Optional Step4: <br> Step5: Assessing word relevancy via term frequency-inverse document frequenc...
12,727
<ASSISTANT_TASK:> Python Code: %pylab inline #imshow(C.get_optical_path_map()) #colorbar() #poly,error=C.get_optical_path_map_lsq(order=2) #print(error) #print(poly) def opsystem(lp): L=library.Edmund.get("32494") C=CCD() S=System(complist=[(L,(0,0,lp),(0,-pi,0)),(C,(0,0,570),(0,0,0))],n=1.) R=point_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: Ejercicio Step2: Utilizando otras librerias de python para optimizar el sistema
12,728
<ASSISTANT_TASK:> Python Code: # Download example dataset from msmbuilder.example_datasets import FsPeptide fs_peptide = FsPeptide() fs_peptide.cache() # Work in a temporary directory import tempfile import os os.chdir(tempfile.mkdtemp()) from msmbuilder.dataset import dataset xyz = dataset(fs_peptide.data_dir + "/*.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: The dataset object Step2: Featurization Step3: Intermediate kinetic model Step4: tICA Heatmap Step5: Clustering Step6: MSM Step7: Macrosta...
12,729
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from pandas import Series, DataFrame weather = pd.read_table('daily_weather.tsv') weather.groupby('season_desc').agg({'temp': np.mean}) fix = weather.replace("Fall", "Summer_").replace("Summer", "Spring_").replace("Winter", "Fall_").replace("Spring",...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Various of the columns represent dates or datetimes, but out of the box pd.read_table won't treat them correctly. This makes it hard to (for exa...
12,730
<ASSISTANT_TASK:> Python Code:: model = Sequential() model.add(Embedding(vocab_size, 10, input_length=1)) model.add(LSTM(1000, return_sequences=True)) model.add(LSTM(1000)) model.add(Dense(1000, activation="relu")) model.add(Dense(vocab_size, activation="softmax")) <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:
12,731
<ASSISTANT_TASK:> Python Code: # Für die Standardausgabe benutzen wir die print() Funktion print("Hallo Welt!") # Wir können mit Kommata getrennt auch mehrere Werte ausgeben: print("foo", "bar") # Mit der help() Funktionen zeigen wir uns # die Hilfe der print() Funktion an: help(print) # Ausgabe mit Seperatoren: print(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Einfache Operationen Step2: Genauer betrachtet besteht die Zeile 4 + 34 aus zwei Literalen (4 und 34) und einem Operator (+), die kombiniert de...
12,732
<ASSISTANT_TASK:> Python Code: %pylab inline from matplotlib.pylab import * from pymc3 import * import numpy as np d = np.random.normal(size=(3, 30)) d1 = d[0] + 4 d2 = d[1] + 4 yd = .2*d1 +.3*d2 + d[2] lam = 3 with Model() as model: s = Exponential('s', 1) tau = Uniform('tau', 0, 1000) b = lam * tau ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then define the random variables. Step2: For most samplers, including Metropolis and HamiltonianMC, simply pass a list of variables to sample a...
12,733
<ASSISTANT_TASK:> Python Code: from __future__ import division import numpy as np import pandas as pd import matplotlib.pyplot as plt import os from scipy.cluster.hierarchy import dendrogram, linkage import ggplot as gg import networkx as nx %matplotlib inline data_dir = os.path.join(os.getenv('MDA_DATA_DIR', '/home/m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Data import Step4: The cell below reproduces the logic in the first cell of the original article. It doesn't feel quite as nice to me as the d...
12,734
<ASSISTANT_TASK:> Python Code: gap_fill_by_month = candles.groupby(["month", "gap_filled"]).size() gap_fill_by_month.groupby("month").apply(lambda g: g / g.sum() * 100) gap_fill_by_day_of_week = candles.groupby(["day_of_week", "gap_filled"]).size() gap_fill_by_day_of_week.groupby("day_of_week").apply(lambda g: g / g.s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Month has no discernible effect on gap fill rate. Step2: Monday has a slightly lower gap fill rate.
12,735
<ASSISTANT_TASK:> Python Code: import requests url = 'http://www.tripadvisor.com/' response = requests.get(url) print(response.status_code) #print(response.headers) import requests url = 'http://www.tripadvisor.com/robots.txt' response = requests.get(url) if response.status_code == 200: print(response.status_cod...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the '/robots.txt' file contents Step2: Get the HTML content from the website Step3: Scraping websites Step4: Step 1 Step5: Step 2 Step7:...
12,736
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'snu', 'sandbox-2', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
12,737
<ASSISTANT_TASK:> Python Code: train = pd.read_csv("train.csv") train.describe() # Cleanup Gender and Embarked train['Sex'] = np.where(train['Sex'] == 'male', 0, 1) train['Embarked'] = train['Embarked'].fillna('Z').map(dict(C=0, S=1, Q=2, Z=3)) # AGE -- quickly look at data train['hasage'] = np.isnan(train['Age']) tra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Clean Data Step2: There is a clear difference in the distributions in ages between thoes who survived and not. Also from the table you can see...
12,738
<ASSISTANT_TASK:> Python Code: ! gsutil ls gs://pyspark-workshop/so-posts lines = sc.textFile("gs://pyspark-workshop/so-posts/*") # or a smaller piece of them lines = sc.textFile("gs://pyspark-workshop/so-posts/Posts.xml-*a") lines.take(5) rows = lines.filter(lambda x: x.lstrip().startswith('<row')) import xml.etree...
<SYSTEM_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 check what's inside these files... Step2: Only proper rows with posts Step3: Let's parse this mess... Step4: Better Step5: Let's compu...
12,739
<ASSISTANT_TASK:> Python Code: %matplotlib inline # Common imports import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.linear_model as skl from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import Mi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simple preprocessing examples, breast cancer data and classification Step2: More on Cancer Data Step3: Principal Component Analysis Step4: PC...
12,740
<ASSISTANT_TASK:> Python Code: # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import mne from mne.datasets import sample import matplotlib.pyplot as plt print(__doc__) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' fwd_fname = data_path + '/MEG/sa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Compute sensitivity maps Step2: Show gain matrix a.k.a. leadfield matrix with sensitivity map
12,741
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from __future__ import division, print_function from collections import Counter, defaultdict import re import itertools import random Set = frozenset # Data will be frozensets, so they can't be mutate...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here are some "arbitrary lists" (see panel two of the comic) which we will be using to test out the code. Step2: And here we show how it works ...
12,742
<ASSISTANT_TASK:> Python Code: a = [4,5,6,8,10] for i in a: print(i) # A fragment of `One Hundred Years of Solitude` GGM = 'Many years later, as he faced the firing squad, \ Colonel Aureliano Buendía was to remember that dist \ ant afternoon when his father took him to discover ice. \ At that time Macondo was a vil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Iterating over dictionaries Step2: Iterating over a sequence
12,743
<ASSISTANT_TASK:> Python Code: def regexp_sum(S): n = len(S) if n == 0: return 0 elif n == 1: r, = S return r else: r, *Rs = S return ('+', r, regexp_sum(Rs)) def rpq(p1, p2, Σ, 𝛿, Allowed): if len(Allowed) == 0: AllChars = { c for c in Σ ...
<SYSTEM_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 function rpq assumes there is some <span style="font-variant Step2: The function dfa_2_regexp takes a deterministic <span style="font-varia...
12,744
<ASSISTANT_TASK:> Python Code: cat = True dog = False print(type(cat)) from cities import cities print(cities) first_alb = cities[0] == 'Albuquerque' second_alb = cities[1] == 'Albuquerque' first_last = cities[0] == cities[-1] print(first_alb, second_alb, first_last) crime_rates = [749, 371, 828, 503, 1379, 425, 408,...
<SYSTEM_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 Step2: 3 Step3: 4 Step4: 5 Step5: 6 Step6: 7 Step7: 8
12,745
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for _, 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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
12,746
<ASSISTANT_TASK:> Python Code: def odd_number(num): L=[] for i in range(num): if i%2 == 1: L.append(i) return L %time odd_sample1 = odd_number(100000000) odd_sample1[:20] odd_number1 = [x for x in range(100000000) if x % 2 == 1] odd_number1 = [] for x in range(100000000): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1억 까지의 홀수들의 리스트를 생성하는 걸리는 시간을 확인해보자. Step2: 지금 사용하는 컴퓨터에서는 9초 정도 걸린다. Step3: 이제 질문을 좀 달리하자. Step4: 위 코드에서 아래 부분이 핵심이다. Step5: 이제 조건제시법 2를 구...
12,747
<ASSISTANT_TASK:> Python Code: from pyspark import SparkContext sc = SparkContext('local[*]') from pyspark.sql import SQLContext sqlc = SQLContext(sc) from pyspark.ml.feature import VectorAssembler from pyspark.ml.feature import StandardScaler from pyspark.ml.feature import StringIndexer from pyspark.ml.feature 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: Spark MLLib imports Step2: Unsupervised Learning Step3: Pre-process the data Step4: Transform 60 features into MMlib vectors Step5: Scale fe...
12,748
<ASSISTANT_TASK:> Python Code: age = 33 print(age) nouvelAge = age + 1 print(nouvelAge) input(a) a = input() print(a) print(a*3) b = int(input()) print(b*5) r_cercle = int(input ("Rayon du cercle ?")) pi = 3.14 d_cercle = r_cercle *2 p_cercle =pi*d_cercle a_cercle = pi*r_cercle*r_cercle print("Diametre du cercle ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ci-dessous, on affiche la valeur de la variable age Step2: Ci-dessous, on crée une variable nouvelAge et on lui affecte la valeur de la variabl...
12,749
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.2,<2.3" import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b.add_dataset(phoebe.dataset.orb, compute_times=np.linspace(0,10,10), dataset='orb01', component=['primar...
<SYSTEM_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 always, let's do imports and initialize a logger and a new Bundle. See the building a system tutorial for more details. Step2: And we'll at...
12,750
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd %pylab inline pylab.style.use('ggplot') import seaborn as sns pp_data = pd.read_csv('ccpp.csv') pp_data.head() for c in pp_data.columns: _ = pylab.figure() pp_data.loc[:, c].plot(kind='hist') feature_data = pp_data.drop('AT', axis=1) 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: Attribute Information Step2: Correlation With the Target column Step3: Feature Correlations Step4: Bivariate Analysis Step5: OLS Regression ...
12,751
<ASSISTANT_TASK:> Python Code: def split_data(data, prob): split data into fractions [prob, 1 - prob] results = [], [] for row in data: results[0 if random.random() < prob else 1].append(row) return results def train_test_split(x, y, test_pct): data = zip(x, y) # pair corresponding values ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modeling Step2: When splitting data, it's important to keep input data and target data in the same order Step3: Correctness Step4: Precision ...
12,752
<ASSISTANT_TASK:> Python Code: import math import numpy as np import pandas as pd from scipy import stats from scipy import optimize import emcee import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline clr_plt = sns.color_palette() import models # the true parameters eps_true = 5e-4 t_true = 3e5 rho...
<SYSTEM_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 mathematical (deterministic, forward) model Step2: The data Step3: The gendata Python module is used to generate the dataset (see the note...
12,753
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy 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: Step3: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab...
12,754
<ASSISTANT_TASK:> Python Code: all_df=[] nfiles=15 for i in range(nfiles): filename = 'msample%d.csv' % i print i all_df.append(pd.read_csv(filename, header=None)) all_df[0] Y=[] for i in range(nfiles): Y.append(all_df[i][8]=='Success') Y[1] def map_user(x): if x.startswith('C'): return '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: I here repeat my procedure for generating labeled data and features for training/test data. Step2: I just discovered that my sample sets do not...
12,755
<ASSISTANT_TASK:> Python Code: paired_bp_tn_split?? cc = codes.ix[matched_rna.columns.get_level_values(0)].dropna().unique() r = pd.DataFrame({c: ttest_rel(matched_rna.ix['PLAU'].ix[ti(codes==c)]) for c in cc}).T fig, ax = subplots(figsize=(7,3)) cc = ['HNSC','LUSC','LUAD','BLCA','THCA','BRCA','COAD','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: TPA protease Step2: Collagenase Step3: elastases Step4: Cathepsin
12,756
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed g = 9.81 # m/s^2 l = 0.5 # length of pendulum, in meters tmax = 50. # seconds t = np.linspace(0, tmax, int(100*tmax)) def derivs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Damped, driven nonlinear pendulum Step4: Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the da...
12,757
<ASSISTANT_TASK:> Python Code: apikey = '34b41fe7b9db6c1bd5f8ea3492bca332' # TA-COMMENT: Nice! coordinates = {'San Antonio': '29.4241,-98.4936', 'Miami': '25.7617,-80.1918', 'Central Park': '40.7829,-73.9654'} import requests url = 'https://api.forecast.io/forecast/' + apikey + '/' + coordinates['San Antonio'] respons...
<SYSTEM_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) What's the current wind speed? How much warmer does it feel than it actually is? Step2: 3) The first daily forecast is the forecast for toda...
12,758
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import copy from sklearn.datasets import fetch_mldata from sklearn import cross_validation from sklearn import base from sklearn.linear_model import Lasso 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: Data generation Step2: L1 Step3: Selecting lambda Step4: L2 Step5: Test with only 200 samples Step6: Selecting lambda Step7: Evaluation us...
12,759
<ASSISTANT_TASK:> Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist # Retrieve the training and test data trainX, trainY, testX, testY = mnist.load_data(one_hot=True) # Visualizing the data import matplotli...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Retrieving training and test data Step2: Visualize the training data Step3: Building the network Step4: Training the network Step5: Testing
12,760
<ASSISTANT_TASK:> Python Code: #@title Imports !pip install jax_md import jax.numpy as np import numpy as onp from jax import jit from jax import random from jax import lax from jax.config import config config.update('jax_enable_x64', True) from jax_md import space from jax_md import energy from jax_md import simulate ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 64k Particle LJ System Step2: Prepare the system Step3: Benchmark using fixed size neighbor list. Step4: On an A100 this comes out to 22.4 s ...
12,761
<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...
12,762
<ASSISTANT_TASK:> Python Code: # %matplotlib inline # %config InlineBackend.figure_format='retina' # mac # %load_ext autoreload # %autoreload 2 import pandas as pd import gseapy as gp import matplotlib.pyplot as plt gp.__version__ # read in an example gene list gene_list = pd.read_csv("./tests/data/gene_list.txt",hea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Check gseapy version Step2: 1. (Optional) Convert IDs Using Biomart API Step3: See all supported enrichr library names Step4: 2.1 Assign ...
12,763
<ASSISTANT_TASK:> Python Code: # sphinx_gallery_thumbnail_number = 2 import os.path as op import matplotlib.pyplot as plt 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(ev...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here for convenience we read the evoked dataset from a file. Step2: Notice that the reader function returned a list of evoked instances. This i...
12,764
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup import sys import os sys.path.insert(0, os.path.abspath('..')) import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Batch Normalization Step2: Batch normalization Step3: Batch Normalization Step4: Batch Normalization Step5: Fully Connected Nets with Batch ...
12,765
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import mmlspark # load raw data from small-sized 30 MB CSV file (trimmed to contain just what we use) dataFile = "On_Time_Performance_2012_9.csv" import os, urllib if not os.path.isfile(dataFile): urllib.request.urlretrieve("https://mmlspark.azu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, import the CSV dataset. Step2: Split the dataset into train and test sets. Step3: Train a regressor on dataset with l-bfgs. Step4: Scor...
12,766
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline from sklearn import linear_model x = np.array([[0, 0], [1, 1], [2, 2]]) y = np.array([0, 1, 2]) print(x,y) clf = linear_model.LinearRegression() clf.fit(x, y) print(clf.coef_) x_missing = np.array([...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Tabular data Step2: Normalization Step3: Categorical data Step4: Exercises Step6: Image data Step7: Text Step8: Exercises
12,767
<ASSISTANT_TASK:> Python Code: % matplotlib inline %config InlineBackend.figure_format = 'retina' %load_ext line_profiler from __future__ import division import numpy as np import glob import matplotlib.pyplot as plt import scipy.linalg as sl import enterprise from enterprise.pulsar import Pulsar import enterprise.sign...
<SYSTEM_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 par and tim files Step2: Load pulsars into Pulsar objects Step3: Setup and run a simple noise model on a single pulsar Step4: We can see ...
12,768
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.model_selection import train_test_split from tensorflow import keras img_rows, img_cols = 28, 28 num_classes = 10 def prep_data(raw): y = raw[:, 0] out_y = keras.utils.to_categorical(y, num_classes) x = raw[:,1:] num_images = raw.shape[...
<SYSTEM_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) Start the model Step2: 2) Add the first layer Step3: 3) Add the remaining layers Step4: 4) Compile Your Model Step5: 5) Fit The Model Ste...
12,769
<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[2] 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...
12,770
<ASSISTANT_TASK:> Python Code: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim.summarization import summarize text = "Thomas A. Anderson is a man living two lives. By day he is an " + \ "average computer programmer and by night a hacker known a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We will try summarizing a small toy example; later we will use a larger piece of text. In reality, the text is too small, but it suffices as an ...
12,771
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) type(mnist) mnist.train.images mnist.train.num_examples mnist.test.num_examples mnist.validation.num_examples import matplotlib.pyplot as plt ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Alternative sources of the data just in case Step2: Visualizing the Data Step3: Create the Model Step4: Loss and Optimizer Step5: Create Ses...
12,772
<ASSISTANT_TASK:> Python Code: from poliastro.atmosphere import COESA62, COESA76 from astropy import units as u import numpy as np import matplotlib.pyplot as plt # We build the atmospheric instances coesa62 = COESA62() coesa76 = COESA76() # Create the figure fig, ax = plt.subplots(figsize=(10,10)) ax.set_title("U.S S...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Comparing coesa62 and coesa76 Step2: Temperature, pressure and density distrubutions
12,773
<ASSISTANT_TASK:> Python Code: import numpy as np import string from sklearn.ensemble import GradientBoostingClassifier def read_file(filename): with open(filename) as f: content = f.readlines() y = [line[0] for line in content] X = [line[2:].strip() for line in content] return X,y X_train,...
<SYSTEM_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 file from data and convert to training set and test set (reading from two distinct files) Step2: A simple class that converts the string i...
12,774
<ASSISTANT_TASK:> Python Code: import notebook from __future__ import print_function from jupyter_core.paths import jupyter_data_dir, jupyter_path print(jupyter_data_dir()) print(jupyter_path()) ! sudo jupyter nbextension install sas_kernel/sas_kernel/nbextensions/showSASLog if notebook.nbextensions.check_nbextension...
<SYSTEM_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 Install Systemwide Step2: This python code will check on the nbextension in systemwide folders (user=False is the flag for this) Step3: To ...
12,775
<ASSISTANT_TASK:> Python Code: X = np.linspace(0, 20, 100) def f(x): if x < 7: return 'a', 2. + np.random.random() elif x < 14: return 'b', 4 + np.random.random() else: return 'c', 6 + np.random.random() K, Y = zip(*[f(x) for x in X]) colors = plt.get_cmap('Set1') categories = ['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: LDA is like inverted ANOVA Step2: LDA assumes that the variance in each group is the same, and that the predictor(s) are normally distributed f...
12,776
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import, division, print_function, unicode_literals try: %tensorflow_version 2.x except Exception: pass import tensorflow as tf tf.__version__ # To generate GIFs !python3 -m pip install -q imageio import glob import imageio import matplotlib.pyplot as pl...
<SYSTEM_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 and prepare the dataset Step2: Next, we define our input pipeline using tf.data. The pipeline below reads in train_images as tensor slices...
12,777
<ASSISTANT_TASK:> Python Code: n_colors = 5 # number of possible colors n_bags = 3 # number of bags n_trials = 20 # number of draws from each bag from bayespy import nodes import numpy as np p_colors = nodes.Dirichlet(n_colors * [0.5], plates=(n_bags,)).random() import bayespy.plot as bpplt bpplt.hinton(p_colors)...
<SYSTEM_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 randomly a color distribution for each bag Step2: The concentration parameter $\begin{bmatrix}0.5 & \ldots & 0.5\end{bmatrix}$ makes t...
12,778
<ASSISTANT_TASK:> Python Code: # A dictionary of movie critics and their ratings of a small # set of movies critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0}, 'Gene Seymour': {'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: 1. User-based filtering Step2: This formula calculates the distance, which will be smaller for people who are more similar. Step3: Pearson co...
12,779
<ASSISTANT_TASK:> Python Code: # constants k_B = Boltzmann eta_air = 18.27e-6 # Pa # (J.T.R.Watson (1995)). d_gas = 0.372e-9 #m #(Sone (2007)), ρSiO2 rho_SiO2 = 1800 # #kg/m^3 - Number told to us by T0 = 300 R = 50e-9 # m def mfp(P_gas): mfp_val = k_B*T0/(2**0.5*pi*d_gas**2*P_gas) return mfp_val m_gas = 4.81e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Alternativity one can use Step2: Muddassar and Gieseler's simplified formula for the environmental damping is Step3: Relation 2 Step4: Relati...
12,780
<ASSISTANT_TASK:> Python Code: class User: def __init__(self, user_id): self.user_id = user_id def __repr__(self): return "User({})".format(self.user_id) def sort_notcompare(): users = [User(23), User(3), User(99)] print(users) print(sorted(users, key = lambda u: u...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 另外一种方式是使用 operator.attrgetter() 来代替 lambda 函数: Step2: 讨论
12,781
<ASSISTANT_TASK:> Python Code: import torch import torch.nn as nn from torch.autograd import Variable import torchvision import torchvision.transforms as T import PIL import numpy as np from scipy.misc import imread from collections import namedtuple import matplotlib.pyplot as plt from cs231n.image_utils import SQUEEZ...
<SYSTEM_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 provide you with some helper functions to deal with images, since for this part of the assignment we're dealing with real JPEGs, not CIFAR-10...
12,782
<ASSISTANT_TASK:> Python Code: !mkdir cifar10 !curl -o cifar-10-python.tar.gz https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz !tar -xvzf cifar-10-python.tar.gz -C cifar10 import numpy as np import matplotlib.pyplot as plt %matplotlib inline from cifar import load_CIFAR10 plt.rcParams['figure.figsize'] = (10.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: <h1 align="center">First of all -- Checking Questions</h1> Step2: Соберите нейронку Step3: Вот и всё, пошли её учить Step4: Процесс обучения
12,783
<ASSISTANT_TASK:> Python Code: import cobra from cobra.solvers import get_solver_name from cobra import Model, Reaction, Metabolite from cobra.flux_analysis import parsimonious import pandas as pd from utils import show_map, findBiomarkers # set escher map map_loc = './maps/escher_map_geenen_2012.json' M = cobra.io.loa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Analyze basic flux distributions
12,784
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from dcprogs.likelihood import QMatrix tau = 0.2 qmatrix = QMatrix([[-1, 1, 0], [19, -29, 10], [0, 0.026, -0.026]], 1) from dcprogs.likelihood._methods import exponential_pdfs def plot_exponentials(qmatrix, tau, x0=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: We then create a function to plot each exponential component in the asymptotic expression. An explanation on how to get to these plots can be fo...
12,785
<ASSISTANT_TASK:> Python Code: import zipfile with zipfile.ZipFile(path + "glove.6B.zip","r") as zip_ref: zip_ref.extractall(path) %ls $path import pickle def get_glove(name): with open(path+ 'glove.' + name + '.txt', 'r') as f: lines = [line.split() for line in f] words = [d[0] for d in lines] vecs = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Process the data Step2: Takes just under 2 min, no output. Step3: Looking at the vectors Step4: Here's the first 25 "words" in glove. Step5: ...
12,786
<ASSISTANT_TASK:> Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Semantic Search with Approximate Nearest Neighbors and Text Embeddings Step2: Import the required libraries Step3: 1. Download Sample Data Ste...
12,787
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from spacy.symbols import pobj site_scrape_dict = { # the following represents html selector to retrieve the header + 2 first test paragraphs 'aol.com': '#article-wrapper h1, #article-wrapper > div.article-content > p:nth-child(2) , #article-...
<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: scraping video geo context Step3: create a unique ['url', 'site'] Step4: create a new csv that will hold url to extracted locations (pipe del...
12,788
<ASSISTANT_TASK:> Python Code: # This imports the OpenContextAPI from the api.py file in the # opencontext directory. %run '../opencontext/api.py' import matplotlib.pyplot as plt import matplotlib.cm as cm def make_group_markers_colors_for_df(df, group_col): Makes group markers and colors for consistence in multip...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Below I define two little utility functions to make scatter plots from the data contained in a dataframe that was populated by the OpenContextAP...
12,789
<ASSISTANT_TASK:> Python Code: # Original book version def vector_sum(vectors): return reduce(vector_add, vectors) vectors = [v,w,v,w,v,w] vector_sum(vectors) # Modified version by sc82.choi at Gachon - *은 여러개의 argument를 list로 전환해줌 def vector_sum_modified(vectors): return [sum(value) for value in zip(*vectors)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scalar * Vector의 연산 ex) 2 * [1,2,3,4] = [2,4,6,8] Step3: vector 의 평균 구하기 Step5: Vector dot product Step7: 하나의 vector에서 값 element들을 제곱하여 더한 후 ...
12,790
<ASSISTANT_TASK:> Python Code: from time import clock from scipy.io import mmwrite import matplotlib.pyplot as plt from qutip import * from qutip.piqs import * nnn = 10 N = nnn jj_mat = nnn/2 [jx_mat, jy_mat, jz_mat] = jmat(jj_mat) jp_mat = jx_mat + 1j * jy_mat jm_mat = jx_mat - 1j * jy_mat w0 = 1 kappa = 2 * w0 gg =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Spectrum of the Liouvillian - Strong dissipation limit $\omega_{0} = 0.5 \kappa $ Step2: The Figure above reproduces qualitatively the study p...
12,791
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.grid_search import GridSearchCV from sklearn import datasets, svm import matplotlib.pyplot as plt # Load the digit data digits = datasets.load_digits() # View the features of the first observation digits.data[0:1] # View the target of the first observatio...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create Two Datasets Step2: The target data is a vector containing the image's true digit. For example, the first observation is a handwritten d...
12,792
<ASSISTANT_TASK:> Python Code: import deepchem as dc from deepchem.models.tensorgraph.models.graph_models import GraphConvModel # Load Tox21 dataset tox21_tasks, tox21_datasets, transformers = dc.molnet.load_tox21(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = tox21_datasets model = GraphConvMod...
<SYSTEM_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 use MoleculeNet to load the Tox21 dataset. We need to make sure to process the data in a way that graph convolutional networks can us...
12,793
<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: Fitting Generalized Linear Mixed-effects Models Using Variational Inference Step2: Abstract Step3: We will also do a quick check for availabli...
12,794
<ASSISTANT_TASK:> Python Code: !cat -n Pure.g4 !cat sum.sl !cat -n Simple.g4 !cat sum.ast !antlr4 -Dlanguage=Python3 Simple.g4 from SimpleLexer import SimpleLexer from SimpleParser import SimpleParser import antlr4 %run ../AST-2-Dot.ipynb def main(file): with open(file, 'r') as handle: program_text = 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 grammar shown above does only contain skip actions. The corrsponding grammar that is enriched with actions is stored in the file Simple.g4....
12,795
<ASSISTANT_TASK:> Python Code: import markovify # Get raw text as string with open("brown.txt") as f: text = f.read() # Build the model. text_model = markovify.Text(text) # Print three randomly-generated sentences of no more than 140 characters for i in range(3): print(text_model.make_short_sentence(140)) <...
<SYSTEM_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 Corpus Step2: Build Markov Chain Step3: Generate One Tweet
12,796
<ASSISTANT_TASK:> Python Code: # import libraries # linear algebra import numpy as np # data processing import pandas as pd # data visualization from matplotlib import pyplot as plt # load the data with pandas dataset = pd.read_csv('dataset.csv', header=None) dataset = np.array(dataset) plt.scatter(dataset[:,0], 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: Step2: 1. Implementar o algoritmo K-means Step3: Teste a função criada e visualize os centróides que foram calculados. Step5: 1.2 Definir os clusters...
12,797
<ASSISTANT_TASK:> Python Code: # ←此為Python的註解符號,在這之後的文字不會被當作程式碼執行 # Python不用宣告變數型態,在指定變數的值時即會動態決定其型態 n_solar_mass = 10 # 整數 MASS_SUN = 1.99 * 10 ** 30 # 浮點數 z = complex(3., -1.) # 複數 unit = "kg" ...
<SYSTEM_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: 資料型態(List、Tuple、Dictionary) Step5: tuple 是有順序但不可以變動 Step6: list 是有順序且可以變動 Step7: 雙重list Step8: 須注意...
12,798
<ASSISTANT_TASK:> Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unz...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Chapter 17 Step2: We will show how JSON looks like and how to deal with JSON in Python with the example dictionary shown below. Step3: You can...
12,799
<ASSISTANT_TASK:> Python Code: fruit_season = { 'raspberry': 'May', 'apple' : 'September', 'peach' : 'July', 'grape' : 'August' } print(type(fruit_season)) print(fruit_season) raspberry_season = fruit_season['raspberry'] print(raspberry_season) print(fruit_season['mangos']) fruit_season['st...
<SYSTEM_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 access a value, you index into it similarly to a list using square brackets. Step2: Trying to access a key not in the dictionary throws an e...