Muennighoff/xP3x-sample huggingface dataset:
inputs: Call has the highest mean price, while suicide has the lowest
Plot price for different types

targets: tx = df[df['type'] == 'tx']
call = df[df['type'] == 'call']
create = df[df['type'] == 'create']
suicide = df[df['type'] == 'suicide']

plt.hist(tx['price_gwei'], bins=4000, color='b', alpha=0.7)
plt.xlim(-10,100)
plt.title('tx', fontsize=18)
plt.xlabel('price', fontsize=18)
plt.show()

plt.hist(call['price_gwei'], bins=4000, color='b', alpha=0.7)
plt.xlim(-10,100)
plt.title('call', fontsize=18)
plt.xlabel('price', fontsize=18)
plt.show()

plt.hist(create['price_gwei'], bins=50, color='b', alpha=0.7)
plt.xlim(-10,100)
plt.title('create', fontsize=18)
plt.xlabel('price', fontsize=18)
plt.show()

plt.hist(suicide['price_gwei'], bins=10, color='b', alpha=0.7)
plt.xlim(-10,100)
plt.title('suicide', fontsize=18)
plt.xlabel('price', fontsize=18)
plt.show()
inputs: 4. Alltogether

targets: ns1 = NS('n', dim=2).truncate(2.0, 0.8, lambda m: np.sum(np.abs(m), axis=1)) + 4
ns2 = 2 * NS('u', dim=2).truncate(1, expr=lambda m: np.sum(m, axis=1)) - (1, 1)
ns3 = NS('n', dim=2).truncate(1.5, expr=lambda m: np.sum(np.square(m), axis=1)) + (4, 0)
ns4 = ((NS('n', dim=2).truncate(2.5, expr=lambda m: np.sum(np.square(m), axis=1)) * 4)
       .apply(lambda m: m.astype(np.int)) / 4 + (0, 3))
ns = 0.4 & ns1 | 0.2 & ns2 | 0.39 & ns3 | 0.01 & ns4

plt.imshow(np.histogramdd(ns.sample(int(1e6)), bins=100, normed=True)[0])
inputs: %%file my_parametrized_fixture.py

import pytest

def g(a):
    return 2 * a

@pytest.fixture(params=[10, 50, 100])
def numbers(request):
    return request.param
    
def test_g(numbers):
    assert g(numbers) == numbers + numbers
    
def test_2g(numbers):
    assert g(2*numbers) == 4 * numbers

!py.test -v my_parametrized_fixture.py
Given the above code, generate some markdown instructions for it.

targets: 
Extended fixtures
Fixtures can be parametrized, which means they can take multiple values. 
The parameters are given as a list to the keyword params.
To access these parameters inside the fixture definition, one must use the request argument and call the param attribute from request (see below in the my_parametrized_fixture.py file definition)
A test using a parametrized fixture will then correspond to a loop test over the parameter set of the fixture. We define here the fixture numbers that can take 3 values: 10, 50 and 100. Any test using the fixture numbers will run three times, with numbers taking respectively the value 10, 50 and 100 .
inputs: 6.
What combination of countries and varieties are most common? Create a Series whose index is a MultiIndexof {country, variety} pairs. For example, a pinot noir produced in the US should map to {"US", "Pinot Noir"}. Sort the values in the Series in descending order based on wine count.

targets: country_variety_counts = ____

# Check your answer
q6.check()

#%%RM_IF(PROD)%%
country_variety_counts = reviews.groupby(['country', 'variety']).size().sort_values(ascending=False)

q6.assert_check_passed()

#_COMMENT_IF(PROD)_
q6.hint()
#_COMMENT_IF(PROD)_
q6.solution()
inputs: I am working on the file "Day 2 - Unit 3.1.ipynb".
The first task is:
2.3.3 Combining line styles with color abbrevations
The nice thing about plot is that it accepts as an argument the following convenience syntax: We can combine both line styles, marker styles and color into one single 2 (or 3 length string). Here are some examples. 

'-or' means plot a solid line, with a circle marker at the data points in red.
'bD' means plot a blue diamond marker scatter plot. 

We use marker codes like this to tell plot whether to plot a line plot or a scatterplots. This is necessary because from plot point of view, there is no essential difference between one and another; a line plot (or time series plot) is created from a scatter plot by interpolating between succesive entries in the Series passed to plot. 
Here below, we shall use this knowledge to plot a simple scatter plot to show the correlation between percentage change in stock prices of both Google (resp. 3M) and Apple.
Can you write Python code for it?

targets: 
fig3, ax3 = plt.subplots(figsize=(6,6))

marker = ["go", "rD"]
for mark, ticker in zip(marker, tickers[1:]):
    ax3.plot(closing_pct_change["AAPL"], closing_pct_change[ticker], mark, label=ticker, alpha=0.5)
    
ax3.set_xlabel("AAPL Percentage change")
ax3.set_title("Correlation of Percentage changes in closing stock price")
plt.legend(loc="best")
inputs: Astropy provides functionality for reading in and manipulating tabular
data through the astropy.table subpackage. An additional set of
tools for reading and writing ASCII data are provided with the
astropy.io.ascii subpackage, but fundamentally use the classes and
methods implemented in astropy.table.
We'll start by importing the ascii subpackage:

targets: from astropy.io import ascii
inputs: # Running in debug mode we can see all ssh arguments injected via anisble. Discuss the DEBUG output       
!sed -i 's/ansible_password/#ansible_password/' inventory
!ansible -vvv -m ping all

# Use this cell for the exercise
Given the above code, generate some markdown instructions for it.

targets: 
Exercise
Comment out the ansible_password field  in inventory here

guess the expected output without running ansible
inputs: ## run steps of an ipyrad assembly on a specific ipcluster instance
data = ip.Assembly("example")
data.set_params("sorted_fastq_path", "example_empirical_rad/*.fastq.gz")
data.run("1", ipyclient=mpi)
Given the above code, generate some markdown instructions for it.

targets: 
Example of using a Client in an ipyrad assembly
Here we create an Assembly and when we call the .run() command we provide a specific ipyclient object as the target to distribute work on. If you do not provide this option then by default ipyrad will look for an ipcluster instance running on the default profile ("").
inputs: ".iloc()"
Please write code following the instructions in jupyter notebook style.

targets: 
# .iloc slicing at specific location - BY POSITION in the table
# Recall:
# dfg[a:b] by rows
# dfg[[col]] or df[[col1, col2]] by columns
# df.loc[a:b, x:y], by index and column values + location
# df.iloc[3:5,0:2], numeric position in table

dfg.iloc[1:4,3:5] # 2nd to 4th row, 4th to 5th column
inputs: # Notar que los índices se indican como Major_axis
closes = panel_data.ix['Adj Close']
closes
Given the above code, generate some markdown instructions for it.

targets: 
Como antes, solo nos interesan los precios de cierre ajustados...
inputs: Below creates a dataframe for all jobs without salaries, then drops duplicate records from that dataframe.

targets: ## Extracting all fields with missing salaries for analysis and estimation later

indeed.salary = indeed.salary.astype(str)
indeed_missing = indeed[indeed['salary'] == 'None']

## Drop duplicate scraped records
indeed_missing[['title','location','company','salary']].drop_duplicates(inplace = True)
inputs: "Changing the Objectives
The objective function is determined from the objective_coefficient attribute of the objective reaction(s). Currently in the model, there is only one objective reaction, with an objective coefficient of 1."
Please write code following the instructions in jupyter notebook style.

targets: 
model.objective
inputs: # Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from mayavi import mlab
from matplotlib import pyplot as plt
from os import path as op

import mne
from mne.viz import ClickableImage  # noqa
from mne.viz import plot_alignment, snapshot_brain_montage


print(__doc__)

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
path_data = mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat'

# We've already clicked and exported
layout_path = op.join(op.dirname(mne.__file__), 'data', 'image')
layout_name = 'custom_layout.lout'
Given the above code, generate some markdown instructions for it.

targets: 
====================================================
How to convert 3D electrode positions to a 2D image.
====================================================
Sometimes we want to convert a 3D representation of electrodes into a 2D
image. For example, if we are using electrocorticography it is common to
create scatterplots on top of a brain, with each point representing an
electrode.
In this example, we'll show two ways of doing this in MNE-Python. First,
if we have the 3D locations of each electrode then we can use Mayavi to
take a snapshot of a view of the brain. If we do not have these 3D locations,
and only have a 2D image of the electrodes on the brain, we can use the
:class:mne.viz.ClickableImage class to choose our own electrode positions
on the image.
inputs: Again we have a very strong signal present in the recording. That is always nice to see. Analysis again is then straightforward:

targets: #run analysis
wd, m = hp.process(hp.scale_data(data), sample_rate)

#visualise in plot of custom size
plt.figure(figsize=(12,4))
hp.plotter(wd, m)

#display computed measures
for measure in m.keys():
    print('%s: %f' %(measure, m[measure]))
inputs: %sql select * from Students
Given the above code, generate some markdown instructions for it.

targets: 
Проверим, что таблица создана
inputs: "Can you find an even better value for K?"
Please write code following the instructions in jupyter notebook style.

targets: 
# try K=1 through K=25 and record testing accuracy
k_range = range(1, 26)
scores = [] # calculate accuracies for each value of K!

#Now we plot:

import matplotlib.pyplot as plt
# allow plots to appear within the notebook
%matplotlib inline

plt.plot(k_range, scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Testing Accuracy')

# try K=1 through K=25 and record testing accuracy
k_range = range(1, 26)
scores = []
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    scores.append(metrics.accuracy_score(y_test, y_pred))
inputs: !py.test -v spectra_analysis/tests/
Given the above code, generate some markdown instructions for it.

targets: 
<div class="alert alert-success">

<b>EXERCISE</b>:<br>
Same as above, implement tests for the two methods.<br><br>

Advice:

<ul>
  <li>Start by defining a common array for both tests
  <pre><code class="python language-python">
  X = np.array([[0, 0, 0],
                [0, 0, 0],
                [1, 1, 1],
                [1, 1, 1],
                [1, 1, 1],
                [2, 2, 2]])
  </code></pre>
                  </li>
  <li>Compute the expected output of the methods applied on this array</li>
</ul>
</div>

Again, verify that the tests pass.
inputs: "According to the plot it is obvious that male passengers had a significant lower chance of survival in comparison to female passengers. 
3.2 Did the social-economic status determine the chances of survival?"
Please write code following the instructions in jupyter notebook style.

targets: 
################################ Survival regarding the fare ##########################
# Create a dataframe of all fares
fares_df=titanic[["Fare", "Survived"]]
fares=titanic["Fare"]

# Create 20 fare ranges from 0 $ - 300 $ and count how many fares from fares_df belong to each range
num_bins=20
bar_width=300/float(num_bins)
fare_ranges_all=[]
for i in np.arange(0,num_bins,1):
    fare_ranges_all.append(len([x for x in fares if i*bar_width <= x < (i+1)*bar_width]))

# Create a dataframe with fares of passengers who survived
survived_fares=fares_df.ix[(fares_df["Survived"]==1)]["Fare"]

# Determine how many fares of passengers who survived belong in each of the 20 ranges 
fare_ranges_survived=[]
for i in np.arange(0,num_bins,1):
    fare_ranges_survived.append(len([x for x in survived_fares if i*bar_width <= x < (i+1)*bar_width]))

# Handle the case in which a fare range does not contain any counts (to avoid devide by null error during normalization)
for n,i in enumerate(fare_ranges_all):
    if i==0:
      fare_ranges_all[n]=1
 
 
################################ Survival regarding the class ##########################
 
# Get the Groupby object 
g=titanic.groupby(["Survived","Pclass"])

# Count the passengers from each class who not have survived
dead_class_1=g.get_group((0,1))["PassengerId"].count()
dead_class_2=g.get_group((0,2))["PassengerId"].count()
dead_class_3=g.get_group((0,3))["PassengerId"].count()

# Count the passengers from each class who  have survived
survived_class_1=g.get_group((1,1))["PassengerId"].count()
survived_class_2=g.get_group((1,2))["PassengerId"].count()
survived_class_3=g.get_group((1,3))["PassengerId"].count()

# Get the Groupby object
g=titanic.groupby(["Pclass"])
# Count the passengers in each class
passengers_class1=float(g.get_group((1))["PassengerId"].count())
passengers_class2=float(g.get_group((2))["PassengerId"].count())
passengers_class3=float(g.get_group((3))["PassengerId"].count())






# Plot the fare-survival relation

fig, axes = plt.subplots(nrows=1, ncols=2,...
inputs: # PROPERTY ID - DO NOT EDIT !  
DOC.set_id('cmip6.land.nitrogen_cycle.overview')  

# PROPERTY VALUE: 
# Set as follows: DOC.set_value("value")  
# TODO - please enter value(s)

Given the above code, generate some markdown instructions for it.

targets: 
29. Nitrogen Cycle
Land surface nitrogen cycle
29.1. Overview
Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1
Overview of the nitrogen cycle in the land surface
inputs: # Solution goes here

# Solution goes here

# Solution goes here

# Solution goes here

# Solution goes here

# Solution goes here

# Solution goes here

# Solution goes here
Given the above code, generate some markdown instructions for it.

targets: 
Exercise: Suppose we have established that A is taller than B, but we don't know how tall B is.
Now we choose a random woman, C, and find that she is shorter than A by at least 15 cm.  Compute posterior distributions for the heights of A and C.
The average height for women in the U.S. is 163 cm; the standard deviation is 7.3 cm.
inputs: # Run OpenMC
openmc.run()
Given the above code, generate some markdown instructions for it.

targets: 
Now we a have a complete set of inputs, so we can go ahead and run our simulation.
inputs: I am working on the file "1_Radio_Science/1_11_modern_interferometric_arrays.ipynb".
The first task is:
Figure 1.11.7: ASKAP phased-array feed telescope. Credit: CSIRO&#10548;
At the prime focus of each dish is a PAF which is used to form multiple 'beams' and increase the effective field of view of the dish. The dish mount has a 'third-axis' which corrects for the rotation of the PAF due to change in parallactic angle. This axis is necessary to keep the PAF 'beams' fixed to a position in the sky. The details of PAFs are not covered in this book, for those interested see the <cite data-cite='mailloux2005phased'>Phased Array Antenna Handbook</cite> &#10548;.
| Dish Specifications |
|:---:|:---:|
| Optics | Prime Focus |
| Diameter | 12 m|
| $\Delta \theta_{1.4 GHz}$ | 1.22 deg |
Table 1.11.10 Dish specifications for ASKAP
The PAFs operate at L-band, they have a higher system temperature and smaller bandwidth coverage compared to MeerKAT, but can make up for this in survey science by covering a larger field of view for a fixed time.
| Receivers |
|:---:|:---:|
| Band | L |
| $T_{sys}$ | $50 K$ |
| Start Frequency | 700 MHz |
| Stop Frequency | 1800 MHz |
| Total Bandwidth | 1100 MHz |
| Instantaneous Bandwidth | 300 MHz |
| Fractional Bandwidth | 0.18 - 0.35 |
| Polarization | Dual Linear |
Table 1.11.11 Receiver specifications for ASKAP
The phased-array feeds have been upgraded to a second generation version which has greatly reduced the system temperature. Below is a close-up of the first generation 'checker board' PAF. The  green panel is an active component which is used to form multiple digital beams.
Can you write Python code for it?

targets: 
Image(filename='figures/arrays/askap_paf_2010.jpg')
inputs: 3.1 It's All Quite Logical
Read the code in the code cell below.

targets: x = 1
if x > 0 and x < 5:
    print("Joe")
    
if x > 0 or x < 5:
    print("Aled")
    
if not(x > 0):
    print("Sarah")
inputs: I am working on the file "People Watching.ipynb".
The first task is:
Looks reasonable, other than that there are some unlikely outliers of people either living to an unrealistically mature age or worse, dying before they were born. When processing lots of data from Wikipedia you have to expect that you end up with a small number of parsing errors.
By occupation
Now we'll group the data by occupation to get a rough idea of which occupations have the best life expectancy.
Can you write Python code for it?

targets: 
top_jobs = [*df.groupby('occupation').count().sort_values('life_span').reset_index()[['occupation', 'life_span']].tail(60)['occupation']]
life_expentancy = df.dropna().groupby('occupation')['life_span'].mean().sort_values()
life_expentancy
inputs: I am working on the file "Lightcurve/Analyze light curves chunk by chunk - an example.ipynb".
The first task is:
R.m.s. - intensity diagram
This diagram is used to characterize the variability of black hole binaries and AGN (see e.g. Plant et al., arXiv:1404.7498; McHardy 2010 2010LNP...794..203M for a review).
In Stingray it is very easy to calculate.
Setup: simulate a light curve with a variable rms and rate
We simulate a light curve with powerlaw variability, and then we rescale
it so that it has increasing flux and r.m.s. variability.
Can you write Python code for it?

targets: 
from stingray.simulator.simulator import Simulator
from scipy.ndimage.filters import gaussian_filter1d
from stingray.utils import baseline_als
from scipy.interpolate import interp1d


np.random.seed(1034232)
# Simulate a light curve with increasing variability and flux
length = 10000
dt = 0.1
times = np.arange(0, length, dt)

# Create a light curve with powerlaw variability (index 1), 
# and smooth it to eliminate some Gaussian noise. We will simulate proper
# noise with the `np.random.poisson` function.
# Both should not be used together, because they alter the noise properties.
sim = Simulator(dt=dt, N=int(length/dt), mean=50, rms=0.4)
counts_cont = sim.simulate(1).counts
counts_cont_init = gaussian_filter1d(counts_cont, 200)

# ---------------------
# Renormalize so that the light curve has increasing flux and r.m.s. 
# variability.
# ---------------------


# The baseline function cannot be used with too large arrays. 
# Since it's just an approximation, we will just use one every
# ten array elements to calculate the baseline
mask = np.zeros_like(times, dtype=bool)
mask[::10] = True
print (counts_cont_init[mask])

baseline = baseline_als(times[mask], counts_cont_init[mask], 1e10, 0.001)
base_func = interp1d(times[mask], baseline, bounds_error=False, fill_value='extrapolate')

counts_cont = counts_cont_init - base_func(times)

counts_cont -= np.min(counts_cont)
counts_cont += 1
counts_cont *= times * 0.003
# counts_cont += 500
counts_cont += 500


# Finally, Poissonize it!
counts = np.random.poisson(counts_cont)
plt.plot(times, counts_cont, zorder=10, label='Continuous light curve')
plt.plot(times, counts, label='Final light curve')

plt.legend()
inputs: I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Remove all spaces in the sentence using a string method.
Can you write Python code for it?

targets: 
my_string = "Humpty Dumpty sat on the wall"
# your code here
inputs: <div class="alert alert-danger"><strong>This is how the categorical embeddings are passed into the layers.</strong></div>

targets: class TabularModel(nn.Module):

    def __init__(self, emb_szs, n_cont, out_sz, layers, p=0.5):
        super().__init__()
        self.embeds = nn.ModuleList([nn.Embedding(ni, nf) for ni,nf in emb_szs])
        self.emb_drop = nn.Dropout(p)
        self.bn_cont = nn.BatchNorm1d(n_cont)
        
        layerlist = []
        n_emb = sum((nf for ni,nf in emb_szs))
        n_in = n_emb + n_cont
        
        for i in layers:
            layerlist.append(nn.Linear(n_in,i)) 
            layerlist.append(nn.ReLU(inplace=True))
            layerlist.append(nn.BatchNorm1d(i))
            layerlist.append(nn.Dropout(p))
            n_in = i
        layerlist.append(nn.Linear(layers[-1],out_sz))
            
        self.layers = nn.Sequential(*layerlist)
    
    def forward(self, x_cat, x_cont):
        embeddings = []
        for i,e in enumerate(self.embeds):
            embeddings.append(e(x_cat[:,i]))
        x = torch.cat(embeddings, 1)
        x = self.emb_drop(x)
        
        x_cont = self.bn_cont(x_cont)
        x = torch.cat([x, x_cont], 1)
        x = self.layers(x)
        return x

torch.manual_seed(33)
model = TabularModel(emb_szs, conts.shape[1], 2, [200,100], p=0.4) # out_sz = 2

model
inputs: I am working on the file "01-titanic/statement-importance/statement-importance.ipynb".
The first task is:
2. Оставьте в выборке четыре признака: класс пассажира (Pclass), цену билета (Fare), возраст пассажира (Age) и его пол (Sex).
3. Обратите внимание, что признак Sex имеет строковые значения.
4. Выделите целевую переменную — она записана в столбце Survived.
5. В данных есть пропущенные значения — например, для некоторых пассажиров неизвестен их возраст. Такие записи при чтении их в pandas принимают значение nan. Найдите все объекты, у которых есть пропущенные признаки, и удалите их из выборки.
Can you write Python code for it?

targets: 
df_no_missing = df[['Survived', 'Pclass', 'Fare', 'Age', 'Sex']].dropna()
X_train_withStrings = df_no_missing[['Pclass', 'Fare', 'Age', 'Sex']]
y_train = df_no_missing['Survived']

def strings_to_int(df, target_column):
    df_mod = df.copy()
    targets_to_rename = df_mod[target_column].unique()
    map_to_int = {name: n for n, name in enumerate(targets_to_rename)}
    df_mod[target_column] = df_mod[target_column].replace(map_to_int)

    return df_mod

X_train = strings_to_int(X_train_withStrings, "Sex")
X_train.head()
inputs: ""break" and "continue" statements
break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples:"
Please write code following the instructions in jupyter notebook style.

targets: 
# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)
inputs: # !!!! Also must have MM folder on system PATH
# mm_version = 'C:\Micro-Manager-1.4'
# cfg = 'C:\Micro-Manager-1.4\SetupNumber2_05102016.cfg'
mm_version = 'C:\Program Files\Micro-Manager-2.0beta'
cfg = 'C:\Program Files\Micro-Manager-2.0beta\Setup2_20170413.cfg'

import sys
sys.path.insert(0, mm_version) # make it so python can find MMCorePy
import MMCorePy

from PIL import Image

core = MMCorePy.CMMCore()
core.loadSystemConfiguration(cfg)
core.setProperty("Spectra", "White_Enable", "1")
core.waitForDevice("Spectra")

core.setProperty("Cam Andor_Zyla4.2", "Sensitivity/DynamicRange", "16-bit (low noise & high well capacity)") # NEED TO SET CAMERA TO 16 BIT (ceiling 12 BIT = 4096)

core.setProperty("Spectra", "White_Enable", "0")
Given the above code, generate some markdown instructions for it.

targets: 
Micromanager
inputs: 5. Spectral clustering algorithm
5.1. Affinity matrix
Compute and visualize the affinity matrix

targets: from sklearn.metrics.pairwise import rbf_kernel

gamma = 5
sf = 4
Xsub = X[0::sf]
print Xsub.shape
gamma = 0.001
K = rbf_kernel(Xsub, Xsub, gamma=gamma)

plt.imshow(K, cmap='hot')
plt.colorbar()
plt.title('RBF Affinity Matrix for gamma = ' + str(gamma))
plt.grid('off')
plt.show()

from sklearn.cluster import SpectralClustering

spc = SpectralClustering(n_clusters=50, gamma=gamma, affinity='rbf')
y_kmeans = spc.fit_predict(Xsub)

plt.scatter(Xsub[:,0], Xsub[:,1], c=y_kmeans, s=5, cmap='rainbow', linewidth=0.0)
plt.axis('equal')
plt.show()

print X[:,1]
inputs: "Again, define the placeholders, variables, model, and cost function:"
Please write code following the instructions in jupyter notebook style.

targets: 
train_size, num_features = xs.shape

X = tf.placeholder("float", shape=[None, num_features])
Y = tf.placeholder("float", shape=[None, num_labels])

W = tf.Variable(tf.zeros([num_features, num_labels]))
b = tf.Variable(tf.zeros([num_labels]))
y_model = tf.nn.softmax(tf.matmul(X, W) + b)

cost = -tf.reduce_sum(Y * tf.log(y_model))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

correct_prediction = tf.equal(tf.argmax(y_model, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
inputs: "&nbsp;

https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
747. Largest Number At Least Twice of Others
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Example 1:
```
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.
```
Example 2:
Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. 
Note:
nums will have a length in the range [1, 50].
Every nums[i] will be an integer in the range [0, 99]."
Please write code following the instructions in jupyter notebook style.

targets: 

a=[1,2,4,5,3]

def find_largest(a):
    m = max(a)
    i = a.index(m)
    del a[i]
    m2 = max(a)

    return i if m==0 or m/m2>=2 else -1

find_largest(a)
inputs: # 3-qubit W state, first and second steps
n = 3
q = QuantumRegister(n) 
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c) 
        
W_states.x(q[2]) #start is |100>
F_gate(W_states,q,2,1,3,1) # Applying F12
F_gate(W_states,q,1,0,3,2) # Applying F23
       
for i in range(3) :
    W_states.measure(q[i] , c[i]) 

shots = 1024
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print('start W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp)
result = execute(W_states, backend=backend, shots=shots)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print('end   W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp)
plot_histogram(result.result().get_counts(W_states))
Given the above code, generate some markdown instructions for it.

targets: 
Three-qubit W state: adding step 2
In the previous step you obtained an histogram compatible with the following state:
$$ |\varphi_{1} \rangle= F_{1,2}\,  |\varphi_{0} \rangle\,=F_{1,2}\,  \,|1 0 0 \rangle=\frac{1}{\sqrt{3}} \: |1 0 0 \rangle \: + \sqrt{\frac{2}{3}} \: |1 1 0 \rangle $$
NB: Depending on the backend, it happens that the order of the qubits is modified, but without consequence for the state finally reached.
We seem far from the ultimate goal.
Run the following circuit to obtain $|\varphi_{2} \rangle =F_{2,3}\, \, |\varphi_{1} \rangle$
inputs: I am working on the file "NLAhw/hw1/PS1.ipynb".
The first task is:
(3 pts) Set x=s[::20], num_iter=1000 and $\alpha=\frac{1}{5}$. Explain what happens with the convergence if you add small random noise of amplitude $10^{-3}\max(x)$  to $y$. The answer to this question should be an explanation supported by plots and/or tables.
Can you write Python code for it?

targets: 
# Your code is here
inputs: <a id='Numb_alterations'></a>
Exercise 2.19: Number of distinct faces rolled in 6 rolls
Let X count the number of distinct faces rolled in 6 rolls of a fair six-sided die.  For example, if the result of the rolls is (3, 3, 3, 3, 3, 3) then X = 1; if (6, 4, 5, 4, 6, 6) then X=3; etc.  Use the number_distinct_values function defined below to define the RV X on an appropriate probability space.  Then simulate values of X and plot its approximate distribution.  (The number_distinct_values function takes as an input a list of values and returns as an output the number of distinct values in the list. We have used the Python functions set and len.)

targets: def number_distinct_values(x):
    return len(set(x))

number_distinct_values((1, 1, 4))

### Type your commands in this cell and then run using SHIFT-ENTER.
inputs: Argumentos por defecto y argumentos de palabra clave
En la definición de una función, podemos asignar valores por defecto a los argumentos de la función:

targets: def mifunc(x, p=2, debug=False):
    if debug:
        print("evaluando mifunc para x = " + str(x) + " usando el exponente p = " + str(p))
    return x**p
inputs: Create an undirected graph in igraph, from the dataframe edge-list, using Graph.TupleList and specifying directed=False. Print out the graph summary using the summary instance method.

targets: grn_igraph = igraph.Graph.TupleList(interac_grn_unique.values.tolist(), directed=False)
grn_igraph.summary()
inputs: "COMMIT YOUR WORK
Documentation
Along the same lines as testability and resusability is documenation.
While python is easy to read and follow, you will either need to share
your code with others or you will forget what you did."
Please write code following the instructions in jupyter notebook style.

targets: 
help(round)
inputs: Barchart

Ideal for comparing groups within the data set

targets: plt.bar([1, 2, 3, 4], [455, 404, 317, 730], tick_label=["XI", "IX", "VIII","V"], align='center');
plt.xlabel("Districts"); plt.ylabel("Avg price   [10^3 HUF/ m^2]");
plt.title("Real estate prices in Budapest (2016)");
inputs: %R push X   is  equivalent to %R -i X
%R pull X   is  equivalent to %R -o X

targets: b = %R a=resid(lm(Y~X))
%Rpull a
print "a", a
print "b", b
inputs: "<div class="alert alert-success">This value is consistent with what ESA says! $7\,060\,160$ km</div>"
Please write code following the instructions in jupyter notebook style.

targets: 
from IPython.display import HTML

HTML(
"""<blockquote class="twitter-tweet" data-lang="en"><p lang="es" dir="ltr">La <a href="https://twitter.com/esa_es">@esa_es</a> ha preparado un resumen del asteroide <a href="https://twitter.com/hashtag/Florence?src=hash">#Florence</a> 😍 <a href="https://t.co/Sk1lb7Kz0j">pic.twitter.com/Sk1lb7Kz0j</a></p>&mdash; AeroPython (@AeroPython) <a href="https://twitter.com/AeroPython/status/903197147914543105">August 31, 2017</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>"""
)
inputs: "And multiply them by scalars:"
Please write code following the instructions in jupyter notebook style.

targets: 
1.5 * u

-1.5 * u
inputs: # Salah
x = np.array(1,2,3)  

# Benar
x = np.array([1,2,3])

y = np.array([[1,0,0],[0,1,0]])
z = np.array([(1,0,0),(0,1,0)])

y-z
Given the above code, generate some markdown instructions for it.

targets: 
Beberapa kesalahan dalam membuat array seringkali terjadi karena kesalahan pada kurung. Ingat bahwa array ini adalah suatu fungsi, sehingga membutuhkan kurung biasa atau parenthesis sedangkan array membutuhkan kurung siku atau brackets. Pada prakteknya, ketika dimensi array lebih dari satu, setelah mengambil brackets di paling luar, menggunakan parenthesis lagi di dalam tidak masalah.
inputs: "Advance usage: create new procedure
will add description later"
Please write code following the instructions in jupyter notebook style.

targets: 
from ddf_utils.chef.ingredient import Ingredient, ProcedureResult

def multiply_1000(chef, ingredients, result, **options):
    ingredients = [chef.dag.get_node(x) for x in ingredients]
    ingredient = ingredients[0].evaluate()
    
    new_data = dict()
    for k, df in ingredient.get_data().items():
        df_ = df.copy()
        df_[k] = df_[k] * 1000
        new_data[k] = df_
        
    return ProcedureResult(chef, result, ingredient.key, new_data)

chef = Chef()
chef.add_config(ddf_dir=os.path.expanduser('~/src/work/Gapminder/datasets'))

i = '''
id: cpi-datapoints
dataset: ddf--transpint--corrupton
key: country, year
value: "*"
'''

d = yaml.round_trip_load(i)
chef.add_ingredient(**d)

chef.register_procedure(multiply_1000)

chef.add_procedure(collection='datapoints',
                   procedure='multiply_1000',
                   result='res',
                   ingredients=['cpi-datapoints']
                  )

res = chef.run()

res[0].get_data()['cpi'].head(5)

chef.ingredients

chef.ingredients[0].get_data()['cpi'].head()  # the original

chef.to_graph()
inputs: Compute residuals
The GP hyperparameters are fit to the residuals from the ckwn white-noise analysis.

targets: lpf = LPFTM()
pv0 = pd.read_hdf(RFILE_EXT, 'ckwn/fc').median().values

fluxes_m = lpf.compute_transit(pv0)
residuals = [fo-fm for fo,fm in zip(lpf.fluxes, fluxes_m)]
gps = [GPTime(time, res) for time,res in zip(lpf.times, residuals)]
hps = []
inputs: "Because there are several steps in this assignment, we have introduced some stopping points where you can check your code and make sure it is correct before proceeding. To test your intermediate_node_num_mistakes function, run the following code until you get a Test passed!, then you should proceed. Otherwise, you should spend some time figuring out where things went wrong."
Please write code following the instructions in jupyter notebook style.

targets: 
# Test case 1
example_labels = np.array([-1, -1, 1, 1, 1])
if intermediate_node_num_mistakes(example_labels) == 2:
    print 'Test passed!'
else:
    print 'Test 1 failed... try again!'

# Test case 2
example_labels = np.array([-1, -1, 1, 1, 1, 1, 1])
if intermediate_node_num_mistakes(example_labels) == 2:
    print 'Test passed!'
else:
    print 'Test 2 failed... try again!'
    
# Test case 3
example_labels = np.array([-1, -1, -1, -1, -1, 1, 1])
if intermediate_node_num_mistakes(example_labels) == 2:
    print 'Test passed!'
else:
    print 'Test 3 failed... try again!'
inputs: Data Manipulation (Plots)
Now that we have the data easily accessible in python, lets look at how to plot it. <code>Pandas</code> allows you to use matplotlib to plot, however it is done using methods built into pandas.
Although the methods to create an manipulate plots are built into <code>Pandas</code>, we will still have to import matplotlib to save and show the plots.

targets: import matplotlib.pyplot as plt
inputs: I am working on the file "NSC2006/labo1/labo_NSC2006_donnees_multidimentionnelles_Octave.ipynb".
The first task is:
<font color="red"> <ol start="11">

<h4><li> Vous allez compléter, à partir du fichier , les 4 lignes de code
    manquante à l’interieure de la boucle pour tracer tous les essais
    (47) dans une même figure. Le résultat ressemblerait à la figure
    suivante: </li></h4>
&lt;/ol&gt;&lt;/font&gt;
Can you write Python code for it?

targets: 
%%matlab
% Charger les donnees
load('Chap17_Data')
% Preparer une figure
figure 
% permettre la superposition de plusieurs graphiques dans la meme figure
hold on 
% Donner un label à l'axe des x
xlabel('Temp (sec)'); 
% Donner un label à l'axe des y
ylabel('Essai #');
% Ajuster les limites de l'axe des y
ylim([0 length(spike)]);

for num_spike = 1:length(spike) %faire une boucle pour tout les essaies
    t = spike(num_spike).times; %definir la variable pour chaque essai
    for num_temps=1:length(t) %faire une boucle pour tous les points temps
        line([t(num_temps) t(num_temps)], [0+(num_spike-1) 1+(num_spike-1)]); %dessiner une line pour chaque point temps t1(i) avec longueur de 1
    end
end
inputs: <a id='model2'></a>
(IMPLEMENTATION) Model 2: CNN + RNN + TimeDistributed Dense
The architecture in cnn_rnn_model adds an additional level of complexity, by introducing a 1D convolution layer.  
<img src="images/cnn_rnn_model.png" width="100%">
This layer incorporates many arguments that can be (optionally) tuned when calling the cnn_rnn_model module.  We provide sample starting parameters, which you might find useful if you choose to use spectrogram audio features.  
If you instead want to use MFCC features, these arguments will have to be tuned.  Note that the current architecture only supports values of 'same' or 'valid' for the conv_border_mode argument.
When tuning the parameters, be careful not to choose settings that make the convolutional layer overly small.  If the temporal length of the CNN layer is shorter than the length of the transcribed text label, your code will throw an error.
Before running the code cell below, you must modify the cnn_rnn_model function in sample_models.py.  Please add batch normalization to the recurrent layer, and provide the same TimeDistributed layer as before.

targets: model_2 = cnn_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features
                        filters=200,
                        kernel_size=11, 
                        conv_stride=2,
                        conv_border_mode='valid',
                        units=200)
inputs: Below, the jupyter magic command %%capture silently discards the output that is produced by the notebook Tic-Tac-Toe.ipynb.

targets: %%capture
%run Tic-Tac-Toe.ipynb
inputs: # for random forest
confusion_matrix(y_train_5, forest_clf.predict(X_train))

confusion_matrix(y_train_5, y_train_5)  # if the prediction is 100% accurate
Given the above code, generate some markdown instructions for it.

targets: 
Where each row represents a actual class and each column represents a predicted class.
inputs: #plt.figure()
plt.rcParams['figure.figsize'] = (6, 3)

i = 0
for track2_image_file in ["data/track_2_1.jpg", "data/track_2_2.jpg", "data/track_2_3.jpg"]:
    track2_image = load_img(track2_image_file)
    track2_image = img_to_array(track2_image).astype(np.uint8)
    track2_image = track2_image[55:135, :, :]
    track2_image = imresize(track2_image, (32, 16, 3))
    
    yuv = cv2.cvtColor(track2_image.astype("uint8"), cv2.COLOR_RGB2HSV)
    yuv[:, :, 0] = yuv[:, :, 0] * 0
    yuv[:, :, 2] = yuv[:, :, 2] * 0
    
    plt.subplot(1, 3, i+1)
    plt.imshow(yuv)
    plt.axis('off')
    
    i += 1
Given the above code, generate some markdown instructions for it.

targets: 
Show some examples from Track 2 with cropping, HSV (only S channel)
inputs: As we mentioned, the created op is actually a protobuf object. Let's show the content.

targets: print("Type of the created op is: {}".format(type(op)))
print("Content:\n")
print(str(op))
inputs: I am working on the file "09_up_and_running_with_tensorflow.ipynb".
The first task is:
Next, let's use the %tensorboard extension to start the TensorBoard server. We need to point it to the root log directory:
Can you write Python code for it?

targets: 
%tensorboard --logdir {root_logdir}
inputs: Como é feita a avaliação quando um dos operadores é uma função? Como é feita a avaliação quando uma função é aplicada a uma expressão?
Exercício:
A função abaixo devolve o primeiro caracter duma \emph{string}:

targets: def primeiro(s):
    return s[0]
inputs: "<div class="alert alert-success">

<b>EXERCISE</b>

 <ul>
  <li>Make a bar plot with pandas of the mean of each of the stations in the year 2012 (check the documentation of Pandas plot to adapt the rotation of the labels) and make sure all bars have the same color.</li>
  <li>Using the matplotlib objects, change the y-label to 'NO$_2$ concentration (µg/m³)</li>
  <li>Add a 'darkorange' horizontal line on the ax for the y-value 40 µg/m³ (command for horizontal line from matplotlib: <code>axhline</code>).</li>
  <li><a href="visualization_01_matplotlib.ipynb">Place the text</a> 'Yearly limit is 40 µg/m³' just above the 'darkorange' line.</li>
</ul>

</div>"
Please write code following the instructions in jupyter notebook style.

targets: 
fig, ax = plt.subplots()
data['2012':].mean().plot(kind='bar', ax=ax, rot=0, color='C0')
ax.set_ylabel("NO$_2$ concentration (µg/m³)")
ax.axhline(y=40., color='darkorange')
ax.text(0.01, 0.48, 'Yearly limit is 40 µg/m³',
        horizontalalignment='left', fontsize=13, 
        transform=ax.transAxes, color='darkorange');
inputs: Configurations

targets: vocab = (" $%'()+,-./0123456789:;=?ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "\\^_abcdefghijklmnopqrstuvwxyz{|}\n")
graph_path = r"./graphs"
test_text_path = os.path.normpath(r"../Dataset/arvix_abstracts.txt")
batch_size=50
model_param_path=os.path.normpath(r"./model_checkpoints")
inputs: 2D Histogram
Now let's say we have multiple input arrays. We can calculate their joint distribution:

targets: db = xr.DataArray(np.random.randn(nt, nx), dims=['time', 'x'],
                  name='bar') - 2

histogram(da, db, bins=[bins, bins]).plot()
inputs: "Class argument explanation

gens=1 :: # of generations. Gen 1 is the mother. Each subsequent gen is composed of daughters that become mothers.
y_end=100 :: Simulation end year.
lifespan=80 :: Lifespan of each generation (e.g., gen 1 is born in year 0 and dies in year 80). 
brth_age=25 :: Age at which each generation gives birth. A birth schedule can be input, as well, using an embedded class function. 
average_lact_time=[0.5]*5 :: an array (must have at least as many elements as # of gens), describing the lactation time period in years. 
k_lac=[1e-2] * 5 :: an array (must have at least as many elements as # of gens), describing the 1st order lactation kinetic rate coefficient.  time period in years [1/years]. 
k_elim=[np.log(2) / 5] * 5 ::  an array (must have at least as many elements as # of gens), describing the 1st order congener elemination kinetic rate coefficient [1/years]. Kinetics can also be determined by inspection of the biomonitoring data for an individual congener, as well. 
odes_in_each_generation=2 :: the number of ode's in each gen (e.g., 2: one for body mass and one for concentration of congener in person).

Problem statement
In this example, let's solve some problems: 
1. What is the time concentration profile of a congener in each of the 5 generations since the introduction of the chemical?
2. Which generation is at the highest risk? 
3. How does the concentration of a congener vary throughout each generation (e.g., what is the concentration of the congener for 20 year olds of each generation)?
initialize the pk_milk class.

assume the birth age is 25, so 5 generations is 125 years for the 5th gen to be born. For a lifespan of 80 years, this means that the simulation should end at: 125 + 80 or 205 years.
assume that the average lactation time for each generation is 10 months. 
assume that the 1st order lactation coefficient is 1e-1 [1/years]. 
assume that the 1st order kinetic elimination coefficient is log(2)/5 [1/years]. Note: k_elim can also be calculated for each congener, which will..."
Please write code following the instructions in jupyter notebook style.

targets: 
pk_milk_base = pk_milk(gens=3, y_end=230,lifespan=80, 
                       brth_age = 25, average_lact_time=[10/12]*5,
                      k_lac=[1e-2] * 5, k_elim=[np.log(2) / 5] * 5)

# calculate and set the delta_t. 
pk_milk_base.dt_from_timesteps_(timestep_variable=10, method='timesteps_per_month')

# calculate and set the number of simulation timesteps
pk_milk_base.n_steps_()
inputs: I am working on the file "2020/01-python-jupyter-notebook/Python-101.ipynb".
The first task is:
Ao dividir dois números (inteiros ou flutuantes), podemos fazer a divisão comum (/) ou divisão inteira (//), onde a última mantém apenas a parte inteira do resultado
Can you write Python code for it?

targets: 
print("Divisao: ",1 / 2)
print("Divisao inteira: ",1 // 2)
inputs: "A very small p-value: this means that the observed mean r value (0.397) is larger than what we would expect by chance. Note that your calculated p-value might deviate slightly from ours given the randomness in a simulation.
Repeat the procedure for all taxa."
Please write code following the instructions in jupyter notebook style.

targets: 
for t in get_taxa_list(taxa):
    print(get_p_value_for_mean_r(taxa, r_values, t, 50000))
inputs: "Counter
Counter是一个简单的计数器，例如，统计字符出现的个数："
Please write code following the instructions in jupyter notebook style.

targets: 
# Counter类的目的是用来跟踪值出现的次数,以字典的键值对形式存储，其中元素作为key，其计数作为value
# 下面这个例子就是使用 Counter 模块统计一段句子里面所有字符出现次数

from collections import Counter

s = 'A Counter is a dict subclass. '.lower()

c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))

# 是否可以统计中文呢？

s = '他会自己长大远去我们也各自远去'

c = Counter(s)

print(c.most_common(5))

# Counter 举例，用户输入内容

from collections import Counter

s = input('Please input:')

s = s.lower()

c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))

# 读出 Counter 对象中的key 和value

s = 'A Counter is a dict subclass. '.lower()
c = Counter(s)

# 用列表生成式获得 counter 中的 key
list1 = [k for k,v in c.most_common()]

# 用列表生成式获得 counter 中的 value
list2 = [v for k,v in c.most_common()]
print(list1)
print(list2)

# 我们在 notebook 中画个图

import matplotlib.pyplot as plt
 
plt.bar(range(len(list2)), list2,color='rgb',tick_label=list1)
plt.show()
inputs: "2) Approximate the probability that the Y is less than 2."
Please write code following the instructions in jupyter notebook style.

targets: 
sims.count_lt(1)/10000
inputs: I am working on the file "GAN/fashion_mnist_gan/fashion_mnist_gan_v2.ipynb".
The first task is:
define the GAN class
the call() method is the 'action' of the model - make it running
Can you write Python code for it?

targets: 


class DCGAN_V2():
  
    def __init__(self):
        
        # The results are a little better when the dimensionality of the random vector is only 10.
        # The dimensionality has been left at 100 for consistency with other GAN implementations.
        self.randomDim = 100

        # Load data
        (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
        X_train = (X_train.astype(np.float32) - 127.5)/127.5
        #self.X_train = np.expand_dims(X_train, -1)
        self.X_train = X_train[:, np.newaxis, :, :]

        self.tensorboard = keras.callbacks.TensorBoard(log_dir=JOB_DIR+ "/logs",
                                                        batch_size=BATCH,
                                                        write_graph=True,
                                                        histogram_freq=0,
                                                        write_images=True,
                                                        write_grads=True)
        #self.checkpointer  = keras.callbacks.ModelCheckpoint(filepath=f'{FLAGS.job_dir}/gan_model.best.hdf5', verbose = 1, save_best_only=True)

        # Optimizer
        self.optimizer = Adam(lr=0.0002, beta_1=0.5)

        self.discriminator = self.build_D()
        self.generator = self.build_G()

        # Combined network
        self.discriminator.trainable = False
        ganInput = Input(shape=(self.randomDim,))
        x = self.generator(ganInput)
        ganOutput = self.discriminator(x)
        self.gan = Model(inputs=ganInput, outputs=ganOutput)
        self.gan.compile(loss='binary_crossentropy', optimizer=self.optimizer)

        self.dLosses = []
        self.gLosses = []


    def build_G(self):
      with tf.variable_scope("Generatoe"):
          # Generator
          generator = Sequential()
          generator.add(Dense(128*7*7, input_dim=self.randomDim, kernel_initializer=initializers.RandomNormal(stddev=0.02)))
          generator.add(LeakyReLU(0.2))
          generator.add(Reshape((128,7, 7)))
         ...
inputs: "Create a subset of the dataset"
Please write code following the instructions in jupyter notebook style.

targets: 
song_df = song_df.head(10000)

#Merge song title and artist_name columns to make a merged column
song_df['song'] = song_df['title'].map(str) + " - " + song_df['artist_name']
inputs: I am working on the file "2.1/tutorials/requiv_crit_contact.ipynb".
The first task is:
Contact Systems
Contact systems are created by passing contact_binary=True to phoebe.default_binary() or by manually adding an envelope and setting the hierarchy correctly.
By default, requiv@primary is the free Parameter, with requiv@secondary, pot@contact_envelope, and fillout_factor@contact_envelope constrained such that there is one single surface defining the envelope.
Can you write Python code for it?

targets: 
print b.filter(qualifier=['requiv', 'pot', 'fillout_factor'])