Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
13,400
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepare a minimal data set. Step1: Plotting separate data columns as separate sub-plots Step2: Plot multiple groups (from same data columns) onto the same plot. Step3: Jake Vanderplas
Python Code: df = pd.DataFrame({'age':[1.,2,3,4,5,6,7,8,9], 'height':[4, 4.5, 5, 6, 7, 8, 9, 9.5, 10], 'gender':['M','F', 'F','M','M','F', 'F','M', 'F'], #'hair color':['brown','black', 'brown', 'blonde', 'brown', 'red', # 'brown'...
13,401
Given the following text description, write Python code to implement the functionality described below step by step Description: CSAL4243 Step1: Logistic Regression Step2: <br> Iris Flower Dataset Using sepal length and width, predict the type of flower. K - Nearest Neighbor (kNN) Classifier Step3: <br> Logistic Re...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors df = pd.read_csv('datasets/exam_dataset1.csv', encoding='utf-8') n_neighbors = 5 X = np.array(df[['exam1','exam2']]) y = np.array(df[['admission']]).ravel() h = ...
13,402
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic ploting Generate coordinate vectors Step1: Generate coordinate matrices Step2: Compute function value Step3: Plot contours Step4: Plot Decision Boundary First, generate the data an...
Python Code: nx, ny = 100, 100 x = np.linspace(-5, 5, nx) y = np.linspace(-5, 5, ny) Explanation: Basic ploting Generate coordinate vectors End of explanation xx, yy = np.meshgrid(x, y, sparse=True) Explanation: Generate coordinate matrices End of explanation z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) Explanation: Com...
13,403
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Get the Data Set index_col=0 to use the first column as the index. Step2: Standardize the Variables Because the KNN classifier predicts the class of a given test obser...
Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> K Nearest Neighbors with Python You've been given a classified data set from a company! They've hidde...
13,404
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: Default Systems Although the default empty Bundle doesn't include a system, there are available constructors that create default systems. To create a simple binary with com...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.Bundle() Explanation: Advanced: Building a System Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment t...
13,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation Student Step3: Explore the Data Play around with view_sentence_range to view different parts of the data. Step6: Implement Preprocessing Function Text to Word I...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation Student: Angel Martinez-Tenor ...
13,406
Given the following text description, write Python code to implement the functionality described below step by step Description: WNixalo 2018/2/11 17 Step1: 1. Consider the polynomial $p(x) = (x-2)^9 = x^9 - 18x^8 + 144x^7 - 672x^6 + 2016x^5 - 4032x^4 + 5376x^3 - 4608x^2 + 2304x - 512$ a. Plot $p(x)$ for $x=1.920,\,1...
Python Code: %matplotlib inline import numpy as np import torch as pt import matplotlib.pyplot as plt plt.style.use('seaborn') Explanation: WNixalo 2018/2/11 17:51 Homework No.1 End of explanation def p(x, mode=0): if mode == 0: return x**9 - 18*x**8 + 144*x**7 - 672*x**6 + 2016*x**5 - 4032*x**4 + 5376*x**3...
13,407
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook is the computational appendix of arXiv Step1: Checking criticial visibility The question whether a qubit or qutrit POVM is simulable by projective measurements bo...
Python Code: from __future__ import print_function, division from fractions import Fraction import numpy as np import numpy.linalg import random import time from povm_tools import basis, check_ranks, complex_cross_product, dag, decomposePovmToProjective, \ enumerate_vertices, find_best_shrinking_factor, get_random_...
13,408
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
13,409
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.eco - Mise en pratique des séances 1 et 2 - Utilisation de pandas et visualisation - correction Correction de l'exercice 3 et disponibilités des velibs. Step1: Exercice 3 - Disponibilité...
Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() from pyensae.datasource import download_data files = download_data("td2a_eco_exercices_de_manipulation_de_donnees.zip", url="https://github.com/sdpython/ensae_teaching_cs/raw/master/_doc/notebooks/td2a_...
13,410
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST Step1: Dataset description Datasource Step2: Distribution of class frequencies Step3: Chisquare test on class frequencies Step4: Display a few sample images Step5: View different ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import * import scipy %matplotlib inline Explanation: MNIST End of explanation training = pd.read_csv("/data/MNIST/mnist_train.csv", header = None) testing = pd.read_csv("/data/MNIST/mnist_test.csv", header = None) X_train,...
13,411
Given the following text description, write Python code to implement the functionality described below step by step Description: Fire up graphlab create Step1: Load some house value vs. crime rate data Dataset is from Philadelphia, PA and includes average house sales price in a number of neighborhoods. The attribute...
Python Code: %matplotlib inline import graphlab Explanation: Fire up graphlab create End of explanation sales = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv/') sales Explanation: Load some house value vs. crime rate data Dataset is from Philadelphia, PA and includes average house sales price in a number o...
13,412
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the 'First steps with pandas'! After this workshop you can (hopefully) call yourselves Data Scientists! Gitter Step1: What is pandas? pandas is an open source, BSD-licensed libra...
Python Code: import platform print('Python: ' + platform.python_version()) import numpy as np print('numpy: ' + np.__version__) import pandas as pd print('pandas: ' + pd.__version__) import scipy print('scipy: ' + scipy.__version__) import sklearn print('scikit-learn: ' + sklearn.__version__) import matplotlib as plt p...
13,413
Given the following text description, write Python code to implement the functionality described below step by step Description: Budyko Transport for Energy Balance Models In this document an Energy Balance Model (EBM) is set up with the energy tranport parametrized through the the budyko type parametrization term (in...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab from climlab import constants as const Explanation: Budyko Transport for Energy Balance Models In this document an Energy Balance Model (EBM) is set up with the energy tranport parametrized through the the budyko type para...
13,414
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Analyzing public cloud and hybrid networks Public cloud and hybrid networks can be hard to debug and secure. Many of the standard tools (e.g., traceroute) do not work in the cloud set...
Python Code: # Import packages %run startup.py bf = Session(host="localhost") def show_first_trace(trace_answer_frame): Prints the first trace in the answer frame. In the presence of multipath routing, Batfish outputs all traces from the source to destination. This function picks the first one. ...
13,415
Given the following text description, write Python code to implement the functionality described below step by step Description: k-Nearest Neighbor (kNN) exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ...
Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt from __future__ import print_function # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplo...
13,416
Given the following text description, write Python code to implement the functionality described below step by step Description: pupil_new explanation (in detail) This is a notebook on explaining deeplabcut workflow (Detailed version) Let's import pupil first (and datajoint) Step1: OK, now let's see what is under pup...
Python Code: import datajoint as dj from pipeline import pupil Explanation: pupil_new explanation (in detail) This is a notebook on explaining deeplabcut workflow (Detailed version) Let's import pupil first (and datajoint) End of explanation dj.ERD(pupil.schema) Explanation: OK, now let's see what is under pupil module...
13,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Convolutional Neural Networks Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - s...
Python Code: %matplotlib inline #change image dim ordering? # from keras import backend # backend.set_image_dim_ordering('th') Explanation: Using Convolutional Neural Networks Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer ...
13,418
Given the following text description, write Python code to implement the functionality described below step by step Description: First, import the processing tools that contain classes and methods to read, plot and process standard unit particle distribution files. Step1: The module consists of a class 'ParticleDistr...
Python Code: import processing_tools as pt Explanation: First, import the processing tools that contain classes and methods to read, plot and process standard unit particle distribution files. End of explanation filepath = './example/example.h5' data = pt.ParticleDistribution(filepath) data.su2si data.dict['x'] Explana...
13,419
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Cheshire objects and methods This file wants to document how one can use Cheshire to query the CLiC database. It fills in the gaps of the official cheshire documentation and it provi...
Python Code: # coding: utf-8 import os from cheshire3.baseObjects import Session from cheshire3.document import StringDocument from cheshire3.internal import cheshire3Root from cheshire3.server import SimpleServer session = Session() session.database = 'db_dickens' serv = SimpleServer(session, os.path.join(cheshire3...
13,420
Given the following text description, write Python code to implement the functionality described below step by step Description: Use of PYBIND11_MAKE_OPAQUE pybind11 automatically converts std Step1: Two identical classes Both of then creates random vectors equivalent to std Step2: Scenarii Three possibilities
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: Use of PYBIND11_MAKE_OPAQUE pybind11 automatically converts std::vector into python list. That's convenient but not necessarily efficient depending on how it is used after that. PYBIND11_MAKE_OPAQUE is used to c...
13,421
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1"><a href="#Seriation-Classification Step1: sklearn-mmadsen is a python package of useful machine learning tools that I'm accumulating for research and ...
Python Code: import numpy as np import networkx as nx import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import cPickle as pickle from copy import deepcopy from sklearn.metrics import classification_report, accuracy_score, confusion_matrix train_graphs = pickle.load(open("train...
13,422
Given the following text description, write Python code to implement the functionality described below step by step Description: Read HIV Data Step1: Read in Clinical Data Step2: Update clinical data with new data provided by Howard Fox Step3: Clean up diabetes across annotation files Step4: All of the patients ar...
Python Code: import os if os.getcwd().endswith('Setup'): os.chdir('..') import NotebookImport from Setup.Imports import * Explanation: Read HIV Data End of explanation c1 = pd.read_excel(ucsd_path + 'DESIGN_Fox_v2_Samples-ChipLAyout-Clinical UNMC-UCSD methylomestudy.xlsx', 'HIV- samples from Old...
13,423
Given the following text description, write Python code to implement the functionality described below step by step Description: Encontro 22 Step1: Início da Atividade 1 Definindo uma função que gera um grafo aleatório tal que a probabilidade de uma aresta existir é c sobre o número de nós Step2: Gerando um grafo pa...
Python Code: import sys sys.path.append('..') import socnet as sn import matplotlib.pyplot as plt %matplotlib inline Explanation: Encontro 22: Mundos Pequenos Importando as bibliotecas: End of explanation from random import random def generate_random_graph(num_nodes, c): g = sn.generate_empty_graph(num_nodes) ...
13,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Reinforcement Learning Step1: Ok, on to the agent itself. I'll present the code in full here, then explain parts in more detail. Step2: You'll see that this is quite similar to the previou...
Python Code: import numpy as np from blessings import Terminal class Game(): def __init__(self, shape=(10,10)): self.shape = shape self.height, self.width = shape self.last_row = self.height - 1 self.paddle_padding = 1 self.n_actions = 3 # left, stay, right self.term ...
13,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: グラフと tf.function の基礎 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 一方、Function は、TensorFl...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
13,426
Given the following text description, write Python code to implement the functionality described below step by step Description: Вопросы по прошлому занятию Что найдет регулярка "^\d+.\d{1,2}.\d{1,2}\s[^A-Z]?$" ? Что делает функция filter(lambda s Step1: Упражнение Написать класс RangeCounter, который принимает начал...
Python Code: a = 1 b = 3 a + b a.__add__(b) type(a) isinstance(a, int) class Animal(object): mammal = True # class variable def __init__(self, name, voice, color="black"): self.name = name self.__voice = voice # "приватный" или "защищенный" атрибут self._color = color # "тип...
13,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Acme Step1: Installation Install Acme Step2: Install the environment library Step3: Install visualization packages Step4: Import Modules Step5: Load an environment We can now load an en...
Python Code: environment_library = 'gym' # @param ['dm_control', 'gym'] Explanation: Acme: Quickstart Guide to installing Acme and training your first D4PG agent. <a href="https://colab.research.google.com/github/deepmind/acme/blob/master/examples/quickstart.ipynb" target="_parent"><img src="https://colab.research.goo...
13,428
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step1: Exploring the Fermi distribution In quantum statistics, the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from IPython.html.widgets import interact, interactive, fixed Explanation: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. End of...
13,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Build a digit classifier app with TensorFlow Lite <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https S...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
13,430
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook used to develop code output from classification is data frame with slave_logs (maybe rename that column?) indicating Step1: Load and clean data Load CLIWOC ship logs Step2: Find d...
Python Code: classifier_algorithm = "Decision Tree" import collections import exploringShipLogbooks import numpy as np import os.path as op import pandas as pd import exploringShipLogbooks.wordcount as wc from fuzzywuzzy import fuzz from sklearn import preprocessing from sklearn.naive_bayes import MultinomialNB from sk...
13,431
Given the following text description, write Python code to implement the functionality described below step by step Description: For more info on Myria, access to the demo cluster, and setting up a cluster Step1: MyriaL Basics First you would scan in whatever tables you want to use in that cell. These are the tables...
Python Code: # myria-python functionality from myria import * # myriaL cell functionality %load_ext myria # connection for myria-python functionality connection = MyriaConnection(rest_url='http://localhost:8753') # same as: http://ec2-52-36-55-94.us-west-2.compute.amazonaws.com:8753 # connection for myriaL cell functio...
13,432
Given the following text description, write Python code to implement the functionality described below step by step Description: FloPy Quick demo on how FloPy handles external files for arrays Step1: make an hk and vka array. We'll save hk to files - pretent that you spent months making this important model property...
Python Code: import os import sys import shutil import numpy as np import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('flopy version: {}'.format(flopy.__version__)) # make a model nlay,nrow,ncol = 10,20,5 model_ws = os.path.join("data","external_demo") if os.path.exists(model_ws): ...
13,433
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: Trying that with a real picture Step2: A color image is a 3D array, where the last dimension has size 3 and represents the red, green, and blue channels Step3: These a...
Python Code: import numpy as np r = np.random.rand(500, 500) from matplotlib import pyplot as plt, cm plt.imshow(r, cmap=cm.gray, interpolation='nearest') Explanation: Introduction: images are numpy arrays A grayscale image is just a 2D array: End of explanation from skimage import data coins = data.coins() print(type(...
13,434
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: Custom training image super resolution model for online predic...
13,435
Given the following text description, write Python code to implement the functionality described below step by step Description: Distribution the way in which something is shared out among a group or spread over an area Random Variable a variable whose value is subject to variations due to chance (i.e. randomness, in ...
Python Code: import pandas as pd import seaborn as sns sns.set(color_codes=True) %matplotlib inline #Import the data cars = pd.read_csv("cars_v1.csv", encoding="ISO-8859-1") #Replace missing values in Mileage with mean cars.Mileage.fillna(cars.Mileage.mean(), inplace=True) sns.distplot(cars.Mileage, kde=False) Explanat...
13,436
Given the following text description, write Python code to implement the functionality described below step by step Description: Практическое задание к уроку 1 (2 неделя). Линейная регрессия Step1: Мы будем работать с датасетом "bikes_rent.csv", в котором по дням записаны календарная информация и погодные условия, ха...
Python Code: import pandas as pd import numpy as np from matplotlib import pyplot as plt %matplotlib inline Explanation: Практическое задание к уроку 1 (2 неделя). Линейная регрессия: переобучение и регуляризация В этом задании мы на примерах увидим, как переобучаются линейные модели, разберем, почему так происходит, и...
13,437
Given the following text description, write Python code to implement the functionality described below step by step Description: SciPy 시작하기 SciPy란 과학기술계산용 함수 및 알고리즘 제공 Home http Step1: scipy.constants 상수 특별 상수 scipy.pi 기타 상수 scipy.constants.XXXX 단위 yotta, zetta, exa, peta, tera, giga, mega, kilo, hecto, deka deci,...
Python Code: rv = sp.stats.norm(loc=10, scale=10) rv.rvs(size=(3, 10), random_state=1) sns.distplot(rv.rvs(size=10000, random_state=1)) xx = np.linspace(-40, 60, 1000) pdf = rv.pdf(xx) plt.plot(xx, pdf) cdf = rv.cdf(xx) plt.plot(xx, cdf) Explanation: SciPy 시작하기 SciPy란 과학기술계산용 함수 및 알고리즘 제공 Home http://www.scipy.org/ Doc...
13,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Competition site http Step1: Constants Step2: Data Loading - Costs Data Step3: - Elevation Data Step4: - Sample Data Parcels that have already been auctioned and exploited (see the gold_...
Python Code: import pandas as pd pd.set_option('display.float_format', '{:.2f}'.format) import numpy as np import matplotlib.pyplot as plt %matplotlib notebook Explanation: Competition site http://www.kaybensoft.com/dublinr/10_competition_site.html Imports End of explanation total_budget = 50000000 gold_price = 1500 # ...
13,439
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: 컨볼루셔널 변이형 오토인코더 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: MNIST 데이터세트 로드하기 각 MNIST 이미지는 원래...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
13,440
Given the following text description, write Python code to implement the functionality described below step by step Description: Tracking Parameters and Metrics for Vertex AI Custom Training Jobs Learning objectives In this notebook, you learn how to Step1: Please ignore the incompatibility errors. Restart the kernel...
Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" # Inst...
13,441
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1><span style="color Step1: Simulate a gene tree with 14 tips and MRCA of 1M generations Step2: Simulate sequences on single gene tree and write to NEXUS When Ne is greater the gene tree...
Python Code: # conda install ipyrad -c conda-forge -c bioconda # conda install mrbayes -c conda-forge -c bioconda # conda install ipcoal -c conda-forge import toytree import ipcoal import ipyrad.analysis as ipa Explanation: <h1><span style="color:gray">ipyrad-analysis toolkit:</span> mrbayes</h1> In these analyses our ...
13,442
Given the following text description, write Python code to implement the functionality described below step by step Description: The EOH (Evolution of Hamiltonian) Algorithm This notebook demonstrates how to use the Qiskit Aqua library to invoke the EOH algorithm and process the result. Further information may be foun...
Python Code: import numpy as np from qiskit_aqua.operator import Operator num_qubits = 2 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) qubitOp = Operator(matrix=temp + temp.T) temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) evoOp = Operator(matrix=temp + temp.T) Explanation: The EOH (Evolution...
13,443
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Sample programs Before working on the following programming examples, it is necessary to upload some text files to Colab. For that, select the folder icon on the left ...
Python Code: from IPython.display import Image from IPython.core.display import HTML Image(url= "https://github.com/OSGeoLabBp/tutorials/blob/master/english/data_processing/lessons/images/file_proc.png?raw=true") Explanation: <a href="https://colab.research.google.com/github/OSGeoLabBp/tutorials/blob/master/english/da...
13,444
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Lecture 3 Step2: <h1>Discrete Fourier Series</h1> Consider a function $f$ periodic over a domain $0\leq x\leq 2\pi$, discretized by $N_x$ points. The longest wavelength wave that can...
Python Code: %matplotlib inline # plots graphs within the notebook %config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format from IPython.display import Image from IPython.core.display import HTML def header(text): raw_html = '<h4>' + str(text) + '</h4>' return ra...
13,445
Given the following text description, write Python code to implement the functionality described below step by step Description: SVC Test This is an example use case of a support vector classifier. We will infer a data classification function from a set of training data. We will use the SVC implementation in the sciki...
Python Code: from sklearn import svm import pandas as pd import pylab as pl import seaborn as sns %matplotlib inline Explanation: SVC Test This is an example use case of a support vector classifier. We will infer a data classification function from a set of training data. We will use the SVC implementation in the sciki...
13,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c) 2017-2020 Serpent-Tools developers team, GTRC THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF...
Python Code: import os mdxFile = os.path.join( os.environ["SERPENT_TOOLS_DATA"], "ref_mdx0.m", ) Explanation: Copyright (c) 2017-2020 Serpent-Tools developers team, GTRC THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABI...
13,447
Given the following text description, write Python code to implement the functionality described below step by step Description: python生成器 本文讲解一下python生成器的基本用法。 生成器的使用场景 当数据量很大的时候,比如从一个超大文本文件中读取内容,如果一下子把数据全部放在列表中,相当于一下子把大量数据放在了内存中,有可能造成内存溢出。那么如何解决呢? 解决方案:不存储所有的数据,而是存储列表元素的生成算法(相当于递推公式),只在使用的时候再根据生成算法生成相应的元素(惰性计算),这就是生...
Python Code: a = (x for x in range(3)) print '【Output】' print type(a) print a.next() print '-----' for x in a: print x Explanation: python生成器 本文讲解一下python生成器的基本用法。 生成器的使用场景 当数据量很大的时候,比如从一个超大文本文件中读取内容,如果一下子把数据全部放在列表中,相当于一下子把大量数据放在了内存中,有可能造成内存溢出。那么如何解决呢? 解决方案:不存储所有的数据,而是存储列表元素的生成算法(相当于递推公式),只在使用的时候再根据生成算法生成相应的元素(惰性计算...
13,448
Given the following text description, write Python code to implement the functionality described below step by step Description: svgpathtools svgpathtools is a collection of tools for manipulating and analyzing SVG Path objects and Bézier curves. Features svgpathtools contains functions designed to easily read, write ...
Python Code: from __future__ import division, print_function # Coordinates are given as points in the complex plane from svgpathtools import Path, Line, QuadraticBezier, CubicBezier, Arc seg1 = CubicBezier(300+100j, 100+100j, 200+200j, 200+300j) # A cubic beginning at (300, 100) and ending at (200, 300) seg2 = Line(20...
13,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Kubeflow E2E MNIST Case Step1: Configure the Docker Registry for Kubeflow Fairing In order to build docker images from your notebook we need a docker registry where the images will be store...
Python Code: !pip show kubeflow-fairing Explanation: Kubeflow E2E MNIST Case: Building, Distributed Training and Serving This example guides you through: 1. Taking an example TensorFlow model and modifying it to support distributed training. 1. Using Kubeflow Fairing to build docker image and launch a TFJob to trai...
13,450
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <h1> ILI285 - Computación Científica I / INF285 - Computación Científica </h1> <h2> Generalized Minimal Residual Method </h2> <h2> <a href="#acknowledgements"> [S]cient...
Python Code: import numpy as np import scipy as sp from scipy import linalg as la import matplotlib.pyplot as plt import scipy.sparse.linalg %matplotlib inline #%load_ext memory_profiler import matplotlib as mpl mpl.rcParams['font.size'] = 14 mpl.rcParams['axes.labelsize'] = 20 mpl.rcParams['xtick.labelsize'] = 14 mpl....
13,451
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2><span style="color Step1: Short tutorial Setup input files and params Step2: calculate distances Step3: save results Step4: Draw the matrix Step5: Draw matrix reordered to match gro...
Python Code: # conda install ipyrad -c bioconda # conda install toyplot -c eaton-lab (optional) import ipyrad.analysis as ipa import toyplot Explanation: <h2><span style="color:gray">ipyrad-analysis toolkit:</span> distance</h2> Key features: Calculate pairwise genetic distances between samples. Filter SNPs to reduce ...
13,452
Given the following text description, write Python code to implement the functionality described below step by step Description: Titanic data exercise Step1: 1. Describe each attribute, both with basic statistics and plots. State clearly your assumptions and discuss your findings. pclass the class a person belongs to...
Python Code: import pandas as pd import numpy as np import glob # to find all files in folder from datetime import datetime from datetime import date, time from dateutil.parser import parse import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set_context('notebook') pd.options.mode.chained_assig...
13,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Passing Messages to Processes As with threads, a common use pattern for multiple processes is to divide a job up among several workers to run in parallel. Effective use of multiple processes...
Python Code: import multiprocessing class MyFancyClass: def __init__(self, name): self.name = name def do_something(self): proc_name = multiprocessing.current_process().name print('Doing something fancy in {} for {}!'.format( proc_name, self.name)) def worker(q): obj = q....
13,454
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy - multidimensional data arrays Ondrej Lexa 2016 Introduction The numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-per...
Python Code: from pylab import * Explanation: NumPy - multidimensional data arrays Ondrej Lexa 2016 Introduction The numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is imp...
13,455
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Iris Flower Data Step2: Standardize Features Step3: Train Support Vector Classifier Step4: Create Previously Unseen Observation Step5: Predict Class Of Observation
Python Code: # Load libraries from sklearn.svm import LinearSVC from sklearn import datasets from sklearn.preprocessing import StandardScaler import numpy as np Explanation: Title: Support Vector Classifier Slug: support_vector_classifier Summary: How to train a support vector classifier in Scikit-Learn Date: 2017-...
13,456
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigm...
13,457
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Linear Regression In this module we will learn how to use data to learn a trend and use this trend to predict new observations. First we load the base libraries. Step1: The easiest w...
Python Code: import csv import numpy as np import scipy as sp import pandas as pd import sklearn as sk import matplotlib.pyplot as plt from IPython.display import Image print('csv: {}'.format(csv.__version__)) print('numpy: {}'.format(np.__version__)) print('scipy: {}'.format(sp.__version__)) print('pandas: {}'.format(...
13,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Flocs Data Demo How to Export Data Both static and collected data can be exported by command make export-data-to-csv. This command creates CSV tables for all models registered in flocs/manag...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd Explanation: Flocs Data Demo How to Export Data Both static and collected data can be exported by command make export-data-to-csv. This command creates CSV tables for all models registered in flocs/management/commands...
13,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Projects Wells are one of the fundamental objects in welly. Well objects include collections of Curve objects. Multiple Well objects can be stored in a Project. On this page, we take a close...
Python Code: import welly welly.__version__ Explanation: Projects Wells are one of the fundamental objects in welly. Well objects include collections of Curve objects. Multiple Well objects can be stored in a Project. On this page, we take a closer look at the Project class. It lets us handle groups of wells. It is rea...
13,460
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'ukesm1-0-ll', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: MOHC Source ID: UKESM1-0-LL Topic: Ocnbgchem Sub-Topics: Tracers. ...
13,461
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'hammoz-consortium', 'sandbox-1', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-1 Topic: Atmoschem ...
13,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Neuron Lang is a python based DSL for naming neurons. Neurons are modelled as collections of phenotypes with semantics backed by Web Ontology Language (OWL2) classes. Neuron Lang provides to...
Python Code: from neurondm import * # set predicates in the event that the default config options do not work # if you cloned the NIF-Ontology into a nonstandard location change ontology_local_repo in devconfig.yaml from pyontutils.namespaces import ilxtr as pred from neurondm import phenotype_namespaces as phns config...
13,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Moon Phase Correlation Analysis Step1: This Wikipedia article has a nice description of how to calculate the current phase of the moon. In code, that looks like this Step2: Let's randomly ...
Python Code: import ujson as json import matplotlib.pyplot as plt import pandas as pd import numpy as np import plotly.plotly as py from moztelemetry import get_pings, get_pings_properties, get_one_ping_per_client from moztelemetry.histogram import Histogram import datetime as dt %pylab inline Explanation: Moon Phase C...
13,464
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Using the Meta-Dataset Data Pipeline This notebook shows how to use meta_dataset’s input pi...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
13,465
Given the following text description, write Python code to implement the functionality described below step by step Description: A neural network from first principles The code below was adpated from the code supplied in Andrew Ng's Coursera course on machine learning. The original code was written in Matlab/Octave an...
Python Code: # Import libraries import numpy as np import matplotlib.pyplot as plt import math from sklearn.metrics import accuracy_score import pickle import sys Explanation: A neural network from first principles The code below was adpated from the code supplied in Andrew Ng's Coursera course on machine learning. The...
13,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a better model Following the baseline model and some feature engineering, we will now build a better predictive model. This will follow a few new patterns Step1: Data Step2: Clean...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import os import sys import sklearn import sqlite3 import matplotlib import numpy as np import pandas as pd import enchant as en import seaborn as sns import statsmodels.api as sm import matplotlib.pyplot as plt from sklearn.ensemble import RandomForest...
13,467
Given the following text description, write Python code to implement the functionality described below step by step Description: Kaggle San Francisco Crime Classification Berkeley MIDS W207 Final Project Step1: DDL to construct table for SQL transformations Step2: Local, individual load of updated data set (with wea...
Python Code: # Import relevant libraries: import time import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn import preprocessing from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.naive_bayes import BernoulliNB fr...
13,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Chapter 13 Copyright 2017 Allen Downey License Step4: Code from previous chapters make_system, plot_results, and calc_total_infected are unchanged. Step6: ...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * Explanation: Modeling and Si...
13,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Key Requirements for the iRF scikit-learn implementation The following is a documentation of the main requirements for the iRF implementation Typical Setup Import the required dependencies I...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer import numpy as np from functools import reduce # Needed for the scikit-learn wrapper function from sklearn.utils import resample from sklearn.ensemble import RandomForestClassifier from math import ceil # Im...
13,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: Air Quality Dataset Regression machine learning task From UCI repository Step2: Insurance Dataset Classification machine learning problem. Formatted data from Kaggle
Python Code: from feature_selector import FeatureSelector import pandas as pd Explanation: Introduction: Testing Feature Selector In this notebook we will test the feature selector using two additional datasets. We will try out many of the FeatureSelector methods on these standard machine learning sets to make sure tha...
13,471
Given the following text description, write Python code to implement the functionality described below step by step Description: Expectation Maximization with Mixtures Implementation of a mixture model using the t distribution. Source D. Peel, G. J. McLachlan; Robust mixture modelling using the t distribution. Statist...
Python Code: actual_mu01 = [0,0] actual_cov01 = [[1,0], [0,1]] actual_df01 = 15 actual_mu02 = [1,1] actual_cov02 = [[.5, 0], [0, 1.5]] actual_df02 = 15 size = 300 x01 = multivariate_t_rvs(m=actual_mu01, S=actual_cov01, df=actual_df01, n=size) x02 = multivariate_t_rvs(m=actual_mu02, S=actual_cov02, df=actual_df02, n...
13,472
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-1', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MIROC Source ID: SANDBOX-1 Sub-Topics: Radiative Forcings. Properties...
13,473
Given the following text description, write Python code to implement the functionality described below step by step Description: Programowanie w języku Python http Step1: Cechy Pythona W Pythonie typ posiadają wartości, a nie zmienne, tak więc Python jest językiem z typami dynamicznymi. Wszystkie wartości przekazy...
Python Code: import this Explanation: Programowanie w języku Python http://mumin.pl/Skrypt_A_do_Z/ https://docs.python.org/3/tutorial/ http://books.icse.us.edu.pl/ Python <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Guido_van_Rossum_OSCON_2006.jpg/320px-Guido_van_Rossum_OSCON_2006.jpg" align='rig...
13,474
Given the following text description, write Python code to implement the functionality described below step by step Description: Iris univariate joint probability distribution Again, it's the Iris dataset (I promise I will unleash some 'real' datasets at some point). I've done a lot of bivariate cluster plots, so I wa...
Python Code: %matplotlib inline import pandas as pd import sys sys.path.append("../../../bayesianpy") import bayesianpy from bayesianpy.network import Builder as builder import logging import os import math import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt import seaborn as sns logger = loggin...
13,475
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Networks Generative Adversarial Networks In Adversarial training procedure two models are trained together. The generative model, G, that estimates the data distributi...
Python Code: # Imports %reload_ext autoreload %autoreload 1 import os, sys sys.path.append('../') sys.path.append('../common') from tools_general import tf, np from IPython.display import Image from tools_train import get_train_params, OneHot, vis_square import imageio # define parameters networktype = 'DCGAN_MNIST' wo...
13,476
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem 1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 belo...
Python Code: x = range(1,10) x def sum_number_mode(a,b,maxbarrier): x = 0 for i in range(1,maxbarrier-1): if i%a == 0 or i%b == 0: x += i return x sum_number_mode(3,5,1001) Explanation: Problem 1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we ...
13,477
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Pyro Michael Zingale, Alice Harpole Stony Brook University Why pyro? Python is a good introductory language&mdash;it helps make the way these algorithms work clearer High lev...
Python Code: import mesh.patch as patch import mesh.boundary as bnd import numpy as np g = patch.Grid2d(16, 16, ng=2) print(g) bc = bnd.BC(xlb="periodic", xrb="periodic", ylb="reflect", yrb="outflow") print(bc) d = patch.CellCenterData2d(g) d.register_var("a", bc) d.create() print(d) Explanation: Introduction to Pyro M...
13,478
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Classify Flowers with Transfer Learning <table class="tfo-notebook-buttons"...
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-2.0 # # Unless re...
13,479
Given the following text description, write Python code to implement the functionality described below step by step Description: Emissions Step1: Loading a configuration from file We will use the following file as an example Step2: The following line loads the setup detailled in that file Step3: Browsing the config...
Python Code: from pygchem import emissions Explanation: Emissions: HEMCO Python API The module pygchem.emissions provides an API for Harvard-NASA Emissions Component (HEMCO). Currently, it allows to read / write HEMCO configuration files and to browse or edit an existing configuration (or create a new configuration fro...
13,480
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Prediction Objectives 1. Build a linear, DNN and CNN model in keras to predict stock market behavior. 2. Build a simple RNN model and a multi-layer RNN model in keras. 3. Comb...
Python Code: import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from google.cloud import bigquery from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential from tensorflow.keras.layers import (Dense, De...
13,481
Given the following text description, write Python code to implement the functionality described below step by step Description: FDMS TME3 Kaggle How Much Did It Rain? II Florian Toque & Paul Willot Data Vize Step1: 13.765.202 lines in train.csv 8.022.757 lines in test.csv Load the dataset Step2: Per wikipedia...
Python Code: # from __future__ import exam_success from __future__ import absolute_import from __future__ import print_function %matplotlib inline import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import pandas as pd import scipy.stats as stats # Sk cheats from sklear...
13,482
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find torch implementation of this notebook here Step1: Imports Step2: Load Data Step3: Let's view some images(Because the images are normalized so we need to first convert them to ...
Python Code: # Install Augmax for Image Augmentation try: import augmax except ModuleNotFoundError: %pip install -qq git+https://github.com/khdlr/augmax.git -q import augmax # Install the jax-resnet try: import jax_resnet except ModuleNotFoundError: %pip install -qq git+https://github.com/n2cholas/...
13,483
Given the following text description, write Python code to implement the functionality described below step by step Description: The problem with my w(\theta) calculation appears to be fairly fundamental Step1: Load up the tptY3 buzzard mocks. Step2: Load up a snapshot at a redshift near the center of this bin. Step...
Python Code: from pearce.mocks import cat_dict import numpy as np from os import path from astropy.io import fits from astropy import constants as const, units as unit import george from george.kernels import ExpSquaredKernel import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot as plt %matplotlib inli...
13,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Previous 2.8 多行匹配模式 问题 你正在试着使用正则表达式去匹配一大块的文本,而你需要跨越多行去匹配。 解决方案 这个问题很典型的出现在当你用点 (.) 去匹配任意字符的时候,忘记了点 (.) 不能匹配换行符的事实。 比如,假设你想试着去匹配 C 语言分割的注释: Step1: 为了修正这个问题,你可以修改模式字符串,增加对换行的支持。比如: Step2: 在这...
Python Code: import re comment = re.compile(r"/\*(.*?)\*/") text1 = '/* this is a comment */' text2 = '''/* this is a multiline comment */ ''' comment.findall(text1) comment.findall(text2) Explanation: Previous 2.8 多行匹配模式 问题 你正在试着使用正则表达式去匹配一大块的文本,而你需要跨越多行去匹配。 解决方案 这个问题很典型的出现在当你用点 (.) 去匹配任意字符的时候,忘记了点 (.) 不能匹配换行符的事实。 比如,...
13,485
Given the following text description, write Python code to implement the functionality described below step by step Description: Executing Squonk services This notebook is an example of executing Squonk services using Python's requests module. It assumes you are executing against the JobExector service running in an O...
Python Code: import requests import json # requests_toolbelt module is used to handle the multipart responses. # Need to `pip install requests-toolbelt` from a terminal to install. This might need doing each time the Notebook pod starts from requests_toolbelt.multipart import decoder # Define some URLs and params base_...
13,486
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: 네트워크 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 네트워크 정의하기 네트워크 API TF-Agents에서는 Keras Networ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
13,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Context John Doe remarked in #AP1432 that there may be too much code in our application that isn't used at all. Before migrating the application to the new platform, we have to analyze which...
Python Code: import pandas as pd coverage = pd.read_csv("../input/spring-petclinic/jacoco.csv") coverage = coverage[['PACKAGE', 'CLASS', 'LINE_COVERED' ,'LINE_MISSED']] coverage['LINES'] = coverage.LINE_COVERED + coverage.LINE_MISSED coverage.head(1) Explanation: Context John Doe remarked in #AP1432 that there may be t...
13,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Row-reduce and variable transformations in non-linear equation systems, an applied example Step1: Let's consider Step2: Let's define the stoichiometry and composition Step3: and now a fun...
Python Code: from __future__ import (absolute_import, division, print_function) from functools import reduce, partial from operator import mul import sympy as sp import numpy as np import matplotlib.pyplot as plt from pyneqsys.symbolic import SymbolicSys, TransformedSys, linear_exprs sp.init_printing() Explanation: Row...
13,489
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploration of pairwise string similarity algorithms Numerous string similarity measuring algirithms are studied below to understand how they work and which one would be the most stuitable. ...
Python Code: import scipy import numpy as np import strsimpy from Bio import pairwise2 from Bio.Seq import Seq from Bio.pairwise2 import format_alignment import matplotlib import matplotlib.pyplot as plt similar_strings = ["user_id", "userid", "UserId", "userID"] Explanation: Exploration of pairwise string similar...
13,490
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Feature Synthesis Deep Feature Synthesis (DFS) is an automated method for performing feature engineering on relational and temporal data. Input Data Deep Feature Synthesis requires stru...
Python Code: import featuretools as ft es = ft.demo.load_mock_customer(return_entityset=True) es Explanation: Deep Feature Synthesis Deep Feature Synthesis (DFS) is an automated method for performing feature engineering on relational and temporal data. Input Data Deep Feature Synthesis requires structured datasets in o...
13,491
Given the following text description, write Python code to implement the functionality described below step by step Description: Quality Check API Example Step1: Create a session. Note the api endpoint, lab-services.ovation.io for Ovation Service Lab. Step2: Create a Quality Check (QC) activity A QC activity determi...
Python Code: import urllib import ovation.lab.workflows as workflows import ovation.session as session Explanation: Quality Check API Example End of explanation s = session.connect(input('Email: '), api='https://lab-services.ovation.io') Explanation: Create a session. Note the api endpoint, lab-services.ovation.io for ...
13,492
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 4 Imports Step1: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 4 Imports End of explanation import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) Explanation: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or node...
13,493
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to Python! I know what you are all thinking...finally! Okay let's check out the basics of Python. I am typing this inside of Jupyter notebook which yields a markdown/programming envi...
Python Code: 3 type(3) 3.0 type(3.0) type('c') type('ca') type("ca") True type(True) type(T) #Not defined unlike R type(true) type(x=3) #An assignment does not return a value. This is different from C/C++/R. x=2 #assignment x x==3 #Boolean Explanation: Welcome to Python! I know what you are all thinking...finally! Okay...
13,494
Given the following text description, write Python code to implement the functionality described below step by step Description: GEE nested covariance structure simulation study This notebook is a simulation study that illustrates and evaluates the performance of the GEE nested covariance structure. A nested covarianc...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm Explanation: GEE nested covariance structure simulation study This notebook is a simulation study that illustrates and evaluates the performance of the GEE nested covariance structure. A nested covariance structure is based on a nested seq...
13,495
Given the following text description, write Python code to implement the functionality described below step by step Description: Sources Bowers, Johnson, Pease, "Prospective hot-spotting Step1: Visualise the risk intensity directly Our random data includes events from the past week, and from one (whole) week ago. We...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import open_cp import open_cp.prohotspot as phs # Generate some random data import datetime times = [datetime.datetime(2017,3,10) + datetime.timedelta(days=np.random.randint(0,10)) for _ in range(20)] times.sort() xc = np.random.random(s...
13,496
Given the following text description, write Python code to implement the functionality described below step by step Description: 如何用Python从海量文本抽取主题? 你在工作、学习中是否曾因信息过载叫苦不迭?有一种方法能够替你读海量文章,并将不同的主题和对应的关键词抽取出来,让你谈笑间观其大略。本文使用Python对超过1000条文本做主题抽取,一步步带你体会非监督机器学习LDA方法的魅力。想不想试试呢? 每个现代人,几乎都体会过信息过载的痛苦。文章读不过来,音乐听不过来,视频看不过来。可是现实的压力...
Python Code: import pandas as pd df = pd.read_csv("datascience.csv", encoding='gb18030') #注意它的编码是中文GB18030,不是Pandas默认设置的编码,所以此处需要显式指定编码类型,以免出现乱码错误。 # 之后看看数据框的头几行,以确认读取是否正确。 df.head() #我们看看数据框的长度,以确认数据是否读取完整。 df.shape Explanation: 如何用Python从海量文本抽取主题? 你在工作、学习中是否曾因信息过载叫苦不迭?有一种方法能够替你读海量文章,并将不同的主题和对应的关键词抽取出来,让你谈笑间观其大略。本文使用P...
13,497
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with the python dyNET package The dyNET package is intended for neural-network processing on the CPU, and is particularly suited for NLP applications. It is a python-wrapper for the ...
Python Code: # we assume that we have the dynet module in your path. # OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is. from dynet import * # create a model and add the parameters. m = Model() pW = m.add_parameters((8,2)) pV = m.add_parameters((1,8)) pb = m.add_parameters((...
13,498
Given the following text description, write Python code to implement the functionality described below step by step Description: Automata Editing Automata Vcsn provides different means to enter automata. One, which also applies to plain Python, is using the automaton constructor Step1: See the documentation of vcsn...
Python Code: import vcsn vcsn.automaton(''' context = "lal_char(ab), z $ -> p <2> p -> q <3>a,<4>b q -> q a q -> $ ''') Explanation: Automata Editing Automata Vcsn provides different means to enter automata. One, which also applies to plain Python, is using the automaton constructor: End of explanation %%automaton a ...
13,499
Given the following text description, write Python code to implement the functionality described below step by step Description: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review...
Python Code: import numpy as np Explanation: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review before we move on to Lecture 3. Remember, to use the numpy module, first it must be ...