The Grey Fairy Book
by Andrew Lang
The Ogre
by Andrew Lang
Additional Information
- Year Published: 1906
- Language: English
- Country of Origin: England
- Source: Lang, A. (Ed.). (1906). The Brown Fairy Book.  Hardly a day passed without his mother saying to him, ‘What are you doing, you useless creature?
Every day the youth committed some fresh piece of folly, till at last Masella, losing all patience, gave him a good beating, which so startled Antonio that he took to his heels and never stopped running till it was dark and the stars were shining in the heavens. He wandered on for some time, not knowing where to go, and at last he came to a cave, at the mouth of which sat an ogre, uglier than anything you can conceive.
He had a huge head and wrinkled brow––eyebrows that met, squinting eyes, a flat broad nose, and a great gash of a mouth from which two huge tusks stuck out. His skin was hairy, his arms enormous, his legs like sword blades, and his feet as flat as ducks'. In short, he was the most hideous and laughable object in the world.
But Antonio, who, with all his faults, was no coward, and was moreover a very civil–spoken lad, took off his hat, and said: ‘Good–day, sir; I hope you are pretty well. Could you kindly tell me how far it is from here to the place where I wish to go?'
When the ogre heard this extraordinary question he burst out laughing, and as he liked the youth's polite manners he said to him: ‘Will you enter my service?'
‘What wages do you give?' replied Antonio.
‘If you serve me faithfully,' returned the ogre, ‘I'll be bound you'll get enough wages to satisfy you.'
So the bargain was struck, and Antonio agreed to become the ogre's servant. He was very well treated, in every way, and he had little or no work to do, with the result that in a few days he became as fat as a quail, as round as a barrel, as red as a lobster, and as impudent as a bantam–cock.
But, after two years, the lad got weary of this idle life, and longed desperately to visit his home again. The ogre, who could see into his heart and knew how unhappy he was, said to him one day: ‘My dear Antonio, I know how much you long to see your mother and sisters again, and because I love you as the apple of my eye, I am willing to allow you to go home for a visit. Therefore, take this donkey, so that you may not have to go on foot; but see that you never say "Bricklebrit" to him, for if you do you'll be sure to regret it.'
Antonio took the beast without as much as saying thank you, and jumping on its back he rode away in great haste; but he hadn't gone two hundred yards when he dismounted and called out ‘Bricklebrit.'
No sooner had he pronounced the word than the donkey opened its mouth and poured forth rubies, emeralds, diamonds and pearls, as big as walnuts.
Antonio gazed in amazement at the sight of such wealth, and joyfully filling a huge sack with the precious stones, he mounted the donkey again and rode on till he came to an inn. Here he got down, and going straight to the landlord, he said to him: ‘My good man, I must ask you to stable this donkey for me. Be sure you give the poor beast plenty of oats and hay, but beware of saying the word "Bricklebrit" to him, for if you do I can promise you will regret it. Take this heavy sack, too, and put it carefully away for me.'
The landlord, who was no fool, on receiving this strange warning, and seeing the precious stones sparkling through the canvas of the sack, was most anxious to see what would happen if he used the forbidden word. So he gave Antonio an excellent dinner, with a bottle of fine old wine, and prepared a comfortable bed for him. As soon as he saw the poor simpleton close his eyes and had heard his lusty snores, he hurried to the stables and said to the donkey ‘Bricklebrit,' and the animal as usual poured out any number of precious stones.
When the landlord saw all these treasures he longed to get possession of so valuable an animal, and determined to steal the donkey from his foolish guest. As soon as it was light next morning Antonio awoke, and having rubbed his eyes and stretched himself about a hundred times he called the landlord and said to him: ‘Come here, my friend, and produce your bill, for short reckonings make long friends.'
When Antonio had paid his account he went to the stables and took out his donkey, as he thought, and fastening a sack of gravel, which the landlord had substituted for his precious stones, on the creature's back, he set out for his home.
No sooner had he arrived there than he called out: ‘Mother, come quickly, and bring table–cloths and sheets with you, and spread them out on the ground, and you will soon see what wonderful treasures I have brought you.'
His mother hurried into the house, and opening the linen–chest where she kept her daughters' wedding outfits, she took out table–cloths and sheets made of the finest linen, and spread them flat and smooth on the ground. Antonio placed the donkey on them, and called out ‘Bricklebrit.' But this time he met with no success, for the donkey took no more notice of the magic word than he would have done if a lyre had been twanged in his ear. Two, three, and four times did Antonio pronounce ‘Bricklebrit,' but all in vain, and he might as well have spoken to the wind.
 The miserable donkey was so distracted at such treatment that, far from pouring out precious stones, it only tore and dirtied all the fine linen.
When poor Masella saw her table–cloths and sheets being destroyed, and that instead of becoming rich she had only been made a fool of, she seized another stick and belaboured Antonio so unmercifully with it, that he fled before her, and never stopped till he reached the ogre's cave.
When his master saw the lad returning in such a sorry plight, he understood at once what had happened to him, and making no bones about the matter, he told Antonio what a fool he had been to allow himself to be so imposed upon by the landlord, and to let a worthless animal be palmed off on him instead of his magic donkey.
Antonio listened humbly to the ogre's words, and vowed solemnly that he would never act so foolishly again. And so a year passed, and once more Antonio was overcome by a fit of home–sickness, and felt a great longing to see his own people again.
Now the ogre, although he was so hideous to look upon, had a very kind heart, and when he saw how restless and unhappy Antonio was, he at once gave him leave to go home on a visit. At parting he gave him a beautiful table–cloth, and said: ‘Give this to your mother; but see that you don't lose it as you lost the donkey, and till you are safely in your own house beware of saying "Table–cloth, open," and "Table–cloth, shut." If you do, the misfortune be on your own head, for I have given you fair warning.'
Antonio set out on his journey, but hardly had he got out of sight of the cave than he laid the table–cloth on the ground and said, ‘Table–cloth, open.' In an instant the table–cloth unfolded itself and disclosed a whole mass of precious stones and other treasures.
When Antonio perceived this he said, ‘Table–cloth, shut,' and continued his journey. He came to the same inn again, and calling the landlord to him, he told him to put the table–cloth carefully away, and whatever he did not to say ‘Table–cloth, open,' or ‘Table–cloth, shut,' to it.
The landlord, who was a regular rogue, answered, ‘Just leave it to me, I will look after it as if it were my own.'
After he had given Antonio plenty to eat and drink, and had provided him with a comfortable bed, he went straight to the table–cloth and said, ‘Table–cloth, open.' It opened at once, and displayed such costly treasures that the landlord made up his mind on the spot to steal it.
When Antonio awoke next morning, the host handed him over a table–cloth exactly like his own, and carrying it carefully over his arm, the foolish youth went straight to his mother's house, and said: ‘Now we shall be rich beyond the dreams of avarice, and need never go about in rags again, or lack the best of food.'
With these words he spread the table–cloth on the ground and said, ‘Table–cloth, open.'
But he might repeat the injunction as often as he pleased, it was only waste of breath, for nothing happened. When Antonio saw this he turned to his mother and said: ‘That old scoundrel of a landlord has done me once more; but he will live to repent it, for if I ever enter his inn again, I will make him suffer for the loss of my donkey and the other treasures he has robbed me of.'
Masella was in such a rage over her fresh disappointment that she could not restrain her impatience, and, turning on Antonio, she abused him soundly, and told him to get out of her sight at once, for she would never acknowledge him as a son of hers again.  When the ogre saw him, he guessed at once what had happened.  You blurt everything out, and your long tongue never ceases wagging for a moment. If you had remained silent in the inn this misfortune would never have overtaken you, so you have only yourself to blame for your present suffering.'
Antonio listened to his master's words in silence, looking for all the world like a whipped dog. When he had been three more years in the ogre's service he had another bad fit of home–sickness, and longed very much to see his mother and sisters again.
So he asked for permission to go home on a visit, and it was at once granted to him. Before he set out on his journey the ogre presented him with a beautifully carved stick and said, ‘Take this stick as a remembrance of me; but beware of saying, "Rise up, Stick," and "Lie down, Stick," for if you do, I can only say I wouldn't be in your shoes for something.'
 You have heard what I said, and forewarned is forearmed.'
This time Antonio thanked his master warmly for all his kindness, and started on his homeward journey in great spirits; but he had not gone half a mile when he said ‘Rise up, Stick.'

Although he had learnt a lesson at some cost to himself, Antonio was full of joy, for he saw a way now of revenging himself on the wicked landlord. Once more he arrived at the inn, and was received in the most friendly and hospitable manner by his host. Antonio greeted him cordially, and said: ‘My friend, will you kindly take care of this stick for me? But, whatever you do, don't say "Rise up, Stick." If you do, you will be sorry for it, and you needn't expect any sympathy from me.'
The landlord, thinking he was coming in for a third piece of good fortune, gave Antonio an excellent supper; and after he had seen him comfortably to bed, he ran to the stick, and calling to his wife to come and see the fun, he lost no time in pronouncing the words ‘Rise up, Stick.'
The moment he spoke the stick jumped up and beat the landlord so unmercifully that he and his wife ran screaming to Antonio, and, waking him up, pleaded for mercy.
When Antonio saw how successful his trick had been, he said: ‘I refuse to help you, unless you give me all that you have stolen from me, otherwise you will be beaten to death.'
The landlord, who felt himself at death's door already, cried out: ‘Take back your property, only release me from this terrible stick;' and with these words he ordered the donkey, the table–cloth, and other treasures to be restored to their rightful owner.
As soon as Antonio had recovered his belongings he said ‘Stick, lie down,' and it stopped beating the landlord at once.
Then he took his donkey and table–cloth and arrived safely at his home with them. This time the magic words had the desired effect, and the donkey and table–cloth provided the family with treasures untold. Antonio very soon married off his sister, made his mother rich for life, and they all lived happily for ever after.


In this project, you'll use generative adversarial networks to generate new images of faces.
You'll be using two datasets in this project:
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using FloydHub, set data_dir
to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe".
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images
.
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.

You'll build the components necessary to build a GANs by implementing the following functions below:
model_inputs
discriminator
generator
model_loss
model_opt
train
This will check to make sure you have the correct version of TensorFlow and access to a GPU
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
Implement the model_inputs
function to create TF Placeholders for the Neural Network. It should create the following placeholders:
image_width
, image_height
, and image_channels
.z_dim
.Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# TODO: Implement Function
real_input = tf.placeholder(tf.float32, (None, image_width, image_height, image_channels), name='input_real')
z_input = tf.placeholder(tf.float32, (None, z_dim), name='input_z')
learning_rate = tf.placeholder(tf.float32)
return real_input, z_input, learning_rate
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Implement discriminator
to create a discriminator neural network that discriminates on images
. This function should be able to reuse the variables in the neural network. Use tf.variable_scope
with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param images: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
# TODO: Implement Function
alpha=0.2
# input layer is 28x 28 x3
with tf.variable_scope('discriminator', reuse=reuse):
x1 = tf.layers.conv2d(images, 64, 5, strides=2, padding='same', activation=None)
relu1 = tf.maximum(x1, alpha * x1)
# here 14 x 14 x 64
x2 = tf.layers.conv2d(x1, 128, 5, strides=2, padding='same', activation=None)
bn2 = tf.layers.batch_normalization(x2, training=True)
relu2 = tf.maximum(bn2, alpha * bn2)
# here 7 x 7 x 128
x3 = tf.layers.conv2d(relu2, 256, 5, strides=2, padding='same', activation=None)
bn3 = tf.layers.batch_normalization(x3, training=True)
relu3 = tf.maximum(alpha * bn3, bn3)
# here 4 x 4 x 256
flat = tf.reshape(relu3, (-1, 4*4*256))
logits = tf.layers.dense(flat, 1)
out = tf.sigmoid(logits)
return out, logits
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
Implement generator
to generate an image using z
. This function should be able to reuse the variables in the neural network. Use tf.variable_scope
with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim
images.
def generator(z, out_channel_dim, is_train=True):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
# TODO: Implement Function
with tf.variable_scope('generator', reuse=not is_train):
alpha = 0.2
# First fully connected layer
x1 = tf.layers.dense(z, 7*7*512)
# Reshape it to start the convolutional stack
x1 = tf.reshape(x1, (-1, 7, 7, 512))
x1 = tf.layers.batch_normalization(x1, training=is_train)
x1 = tf.maximum(alpha * x1, x1)
# 7x7x512 now
x2 = tf.layers.conv2d_transpose(x1, 256, 5, strides=2, padding='same', activation = None)
x2 = tf.layers.batch_normalization(x2, training=is_train)
x2 = tf.maximum(alpha * x2, x2)
# 14x14x256 now
x3 = tf.layers.conv2d_transpose(x2, 128, 5, strides=2, padding='same', activation = None)
x3 = tf.layers.batch_normalization(x3, training=is_train)
x3 = tf.maximum(alpha * x3, x3)
# 28x28x128 now
# Output layer
logits = tf.layers.conv2d_transpose(x3, out_channel_dim, 5, strides=1, padding='same', activation=None)
# 28x28x3 now
out = tf.tanh(logits)
return out
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
Implement model_loss
to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
discriminator(images, reuse=False)
generator(z, out_channel_dim, is_train=True)
def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
# TODO: Implement Function
smooth = 0.1
g_model = generator(input_z, out_channel_dim, is_train=True)
d_model_real, d_logits_real = discriminator(input_real, reuse=False)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real) * (1 - smooth)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))
d_loss = d_loss_real + d_loss_fake
return d_loss, g_loss
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
Implement model_opt
to create the optimization operations for the GANs. Use tf.trainable_variables
to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# TODO: Implement Function
# Get weights and bias to update
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
g_vars = [var for var in t_vars if var.name.startswith('generator')]
# Optimize
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)
return d_train_opt, g_train_opt
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
Implement train
to build and train the GANs. Use the following functions you implemented:
model_inputs(image_width, image_height, image_channels, z_dim)
model_loss(input_real, input_z, out_channel_dim)
model_opt(d_loss, g_loss, learning_rate, beta1)
Use the show_generator_output
to show generator
output while you train. Running show_generator_output
for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator
output every 100 batches.
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
# TODO: Build Model
#tf.reset_default_graph()
_, image_width, image_height, image_channels = data_shape
input_real, input_z, lr = model_inputs(image_width, image_height, image_channels, z_dim)
d_loss, g_loss = model_loss(input_real, input_z, image_channels)
d_opt, g_opt = model_opt(d_loss, g_loss, lr, beta1)
saver = tf.train.Saver()
losses = []
steps = 0
print_every = 10
show_every = 100
n_images = 25
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epoch_count):
for batch_images in get_batches(batch_size):
# TODO: Train Model
steps+=1
batch_images*=2
# sample random noise for G
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))
# run optimizers
_ = sess.run(d_opt, feed_dict = {input_real: batch_images, input_z:batch_z , lr:learning_rate})
_ = sess.run(g_opt, feed_dict = {input_real: batch_images,input_z:batch_z, lr:learning_rate})
if steps % print_every == 0:
train_loss_d = d_loss.eval({input_real:batch_images, input_z:batch_z})
train_loss_g = g_loss.eval({input_z:batch_z})
print("Epoches: {}/{}".format(epoch_i+1, epoch_count),
"d_loss: {:.4f}".format(train_loss_d),
"g_loss: {:.4f}".format(train_loss_g))
losses.append((train_loss_d, train_loss_g))
if steps % show_every == 0:
show_generator_output(sess, n_images, input_z, image_channels, data_image_mode)
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
batch_size = 64
z_dim = 100
learning_rate = 0.0002
beta1 = 0.5
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
batch_size = 32
z_dim = 100
learning_rate = 0.0004
beta1 = 0.5
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.


Arrays provide a lot of methods. To make things easier, in this chapter they are split into groups.
We already know methods that add and remove items from the beginning or the end:
arr.push(...items)
– adds items to the end,arr.pop()
– extracts an item from the end,arr.shift()
– extracts an item from the beginning,arr.unshift(...items)
– adds items to the beginning.Here are a few others.
How to delete an element from the array?
The arrays are objects, so we can try to use delete
:
```js run let arr = [“I”, “go”, “home”];
delete arr[1]; // remove “go”
alert( arr[1] ); // undefined
// now arr = [“I”, , “home”]; alert( arr.length ); // 3 ```
The element was removed, but the array still has 3 elements, we can see that arr.length == 3
.
That’s natural, because delete obj.key
removes a value by the key
. It’s all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.
So, special methods should be used.
The arr.splice method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.
The syntax is:
It modifies arr
starting from the index start
: removes deleteCount
elements and then inserts elem1, ..., elemN
at their place. Returns the array of removed elements.
This method is easy to grasp by examples.
Let’s start with the deletion:
```js run let arr = [“I”, “study”, “JavaScript”];
! arr.splice(1, 1); // from index 1 remove 1 element /!
alert( arr ); // [“I”, “JavaScript”] ```
Easy, right? Starting from the index 1
it removed 1
element.
In the next example we remove 3 elements and replace them with the other two:
```js run let arr = [!“I”, “study”, “JavaScript”,/! “right”, “now”];
// remove 3 first elements and replace them with another arr.splice(0, 3, “Let’s”, “dance”);
alert( arr ) // now [!“Let’s”, “dance”/!, “right”, “now”] ```
Here we can see that splice
returns the array of removed elements:
```js run let arr = [!“I”, “study”,/! “JavaScript”, “right”, “now”];
// remove 2 first elements let removed = arr.splice(0, 2);
alert( removed ); // “I”, “study” <– array of removed elements ```
The splice
method is also able to insert the elements without any removals. For that we need to set deleteCount
to 0
:
```js run let arr = [“I”, “study”, “JavaScript”];
// from index 2 // delete 0 // then insert “complex” and “language” arr.splice(2, 0, “complex”, “language”);
alert( arr ); // “I”, “study”, “complex”, “language”, “JavaScript” ```
````smart header=“Negative indexes allowed” Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here:
```js run let arr = [1, 2, 5];
// from index -1 (one step from the end) // delete 0 elements, // then insert 3 and 4 arr.splice(-1, 0, 3, 4);
alert( arr ); // 1,2,3,4,5
The method arr.slice is much simpler than similar-looking arr.splice
.
The syntax is:
It returns a new array copying to it all items from index start
to end
(not including end
). Both start
and end
can be negative, in that case position from array end is assumed.
It’s similar to a string method str.slice
, but instead of substrings it makes subarrays.
For instance:
```js run let arr = [“t”, “e”, “s”, “t”];
alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3)
alert( arr.slice(-2) ); // s,t (copy from -2 till the end) ```
We can also call it without arguments: arr.slice()
creates a copy of arr
. That’s often used to obtain a copy for further transformations that should not affect the original array.
The method arr.concat creates a new array that includes values from other arrays and additional items.
The syntax is:
It accepts any number of arguments – either arrays or values.
The result is a new array containing items from arr
, then arg1
, arg2
etc.
If an argument argN
is an array, then all its elements are copied. Otherwise, the argument itself is copied.
For instance:
```js run let arr = [1, 2];
// create an array from: arr and [3,4] alert( arr.concat([3, 4]) ); // 1,2,3,4
// create an array from: arr and [3,4] and [5,6] alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6
// create an array from: arr and [3,4], then add values 5 and 6 alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6 ```
Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole:
```js run let arr = [1, 2];
let arrayLike = { 0: “something”, length: 1 };
alert( arr.concat(arrayLike) ); // 1,2,[object Object] ```
…But if an array-like object has a special Symbol.isConcatSpreadable
property, then it’s treated as an array by concat
: its elements are added instead:
```js run let arr = [1, 2];
let arrayLike = { 0: “something”, 1: “else”, ! [Symbol.isConcatSpreadable]: true, /! length: 2 };
alert( arr.concat(arrayLike) ); // 1,2,something,else ```
The arr.forEach method allows to run a function for every element of the array.
The syntax:
For instance, this shows each element of the array:
js run // for each element call alert ["Bilbo", "Gandalf", "Nazgul"].forEach(alert);
And this code is more elaborate about their positions in the target array:
js run ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => { alert(`${item} is at index ${index} in ${array}`); });
The result of the function (if it returns any) is thrown away and ignored.
Now let’s cover methods that search in an array.
The methods arr.indexOf, arr.lastIndexOf and arr.includes have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters:
arr.indexOf(item, from)
– looks for item
starting from index from
, and returns the index where it was found, otherwise -1
.arr.lastIndexOf(item, from)
– same, but looks for from right to left.arr.includes(item, from)
– looks for item
starting from index from
, returns true
if found.For instance:
```js run let arr = [1, 0, false];
alert( arr.indexOf(0) ); // 1 alert( arr.indexOf(false) ); // 2 alert( arr.indexOf(null) ); // -1
alert( arr.includes(1) ); // true ```
Note that the methods use ===
comparison. So, if we look for false
, it finds exactly false
and not the zero.
If we want to check for inclusion, and don’t want to know the exact index, then arr.includes
is preferred.
Also, a very minor difference of includes
is that it correctly handles NaN
, unlike indexOf/lastIndexOf
:
js run const arr = [NaN]; alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN) alert( arr.includes(NaN) );// true (correct)
Imagine we have an array of objects. How do we find an object with the specific condition?
Here the arr.find(fn) method comes in handy.
The syntax is:
let result = arr.find(function(item, index, array) {
// if true is returned, item is returned and iteration is stopped
// for falsy scenario returns undefined
});
The function is called for elements of the array, one after another:
item
is the element.index
is its index.array
is the array itself.If it returns true
, the search is stopped, the item
is returned. If nothing found, undefined
is returned.
For example, we have an array of users, each with the fields id
and name
. Let’s find the one with id == 1
:
```js run let users = [ {id: 1, name: “John”}, {id: 2, name: “Pete”}, {id: 3, name: “Mary”}];
let user = users.find(item => item.id == 1);
alert(user.name); // John ```
In real life arrays of objects is a common thing, so the find
method is very useful.
Note that in the example we provide to find
the function item => item.id == 1
with one argument. That’s typical, other arguments of this function are rarely used.
The arr.findIndex method is essentially the same, but it returns the index where the element was found instead of the element itself and -1
is returned when nothing is found.
The find
method looks for a single (first) element that makes the function return true
.
If there may be many, we can use arr.filter(fn).
The syntax is similar to find
, but filter
returns an array of all matching elements:
let results = arr.filter(function(item, index, array) {
// if true item is pushed to results and the iteration continues
// returns empty array if nothing found
});
For instance:
```js run let users = [ {id: 1, name: “John”}, {id: 2, name: “Pete”}, {id: 3, name: “Mary”}];
// returns array of the first two users let someUsers = users.filter(item => item.id < 3);
alert(someUsers.length); // 2 ```
Let’s move on to methods that transform and reorder an array.
The arr.map method is one of the most useful and often used.
It calls the function for each element of the array and returns the array of results.
The syntax is:
For instance, here we transform each element into its length:
js run let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); alert(lengths); // 5,7,6
The call to arr.sort() sorts the array in place, changing its element order.
It also returns the sorted array, but the returned value is usually ignored, as arr
itself is modified.
For instance:
```js run let arr = [ 1, 2, 15 ];
// the method reorders the content of arr arr.sort();
alert( arr ); // !1, 15, 2/! ```
Did you notice anything strange in the outcome?
The order became 1, 15, 2
. Incorrect. But why?
The items are sorted as strings by default.
Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed "2" > "15"
.
To use our own sorting order, we need to supply a function as the argument of arr.sort()
.
The function should compare two arbitrary values and return:
function compare(a, b) {
if (a > b) return 1; // if the first value is greater than the second
if (a == b) return 0; // if values are equal
if (a < b) return -1; // if the first value is less than the second
}
For instance, to sort as numbers:
```js run function compareNumeric(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; }
let arr = [ 1, 2, 15 ];
! arr.sort(compareNumeric); /!
alert(arr); // !1, 2, 15/! ```
Now it works as intended.
Let’s step aside and think what’s happening. The arr
can be array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of some items. To sort it, we need an ordering function that knows how to compare its elements. The default is a string order.
The arr.sort(fn)
method implements a generic sorting algorithm. We don’t need to care how it internally works (an optimized quicksort or Timsort most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the fn
which does the comparison.
By the way, if we ever want to know which elements are compared – nothing prevents from alerting them:
js run [1, -2, 15, 2, 0, 8].sort(function(a, b) { alert( a + " <> " + b ); return a - b; });
The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible.
````smart header=“A comparison function may return any number” Actually, a comparison function is only required to return a positive number to say “greater” and a negative number to say “less”.
That allows to write shorter functions:
```js run let arr = [ 1, 2, 15 ];
arr.sort(function(a, b) { return a - b; });
alert(arr); // !1, 2, 15/!
````smart header=“Arrow functions for the best” Remember arrow functions? We can use them here for neater sorting:
This works exactly the same as the longer version above. ````
```smart header="Use
localeCompare` for strings" Remember strings comparison algorithm? It compares letters by their codes by default.
For many alphabets, it’s better to use str.localeCompare
method to correctly sort letters, such as Ö
.
For example, let’s sort a few countries in German:
```js run let countries = [‘Österreich’, ‘Andorra’, ‘Vietnam’];
alert( countries.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (wrong)
alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietnam (correct!)
The method arr.reverse reverses the order of elements in arr
.
For instance:
```js run let arr = [1, 2, 3, 4, 5]; arr.reverse();
alert( arr ); // 5,4,3,2,1 ```
It also returns the array arr
after the reversal.
Here’s the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: John, Pete, Mary
. But for us an array of names would be much more comfortable than a single string. How to get it?
The str.split(delim) method does exactly that. It splits the string into an array by the given delimiter delim
.
In the example below, we split by a comma followed by space:
```js run let names = ‘Bilbo, Gandalf, Nazgul’;
let arr = names.split(‘,’);
for (let name of arr) { alert( A message to ${name}.
); // A message to Bilbo (and other names) } ```
The split
method has an optional second numeric argument – a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though:
```js run let arr = ‘Bilbo, Gandalf, Nazgul, Saruman’.split(‘,’, 2);
alert(arr); // Bilbo, Gandalf ```
```smart header="Split into letters" The call to
split(s)with an empty
s` would split the string into an array of letters:
```js run let str = “test”;
alert( str.split(’’) ); // t,e,s,t
The call arr.join(glue) does the reverse to split
. It creates a string of arr
items joined by glue
between them.
For instance:
```js run let arr = [‘Bilbo’, ‘Gandalf’, ‘Nazgul’];
let str = arr.join(‘;’); // glue the array into a string using ;
alert( str ); // Bilbo;Gandalf;Nazgul ```
When we need to iterate over an array – we can use forEach
, for
or for..of
.
When we need to iterate and return the data for each element – we can use map
.
The methods arr.reduce and arr.reduceRight also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array.
The syntax is:
The function is applied to all array elements one after another and “carries on” its result to the next call.
Arguments:
accumulator
– is the result of the previous function call, equals initial
the first time (if initial
is provided).item
– is the current array item.index
– is its position.array
– is the array.As function is applied, the result of the previous function call is passed to the next one as the first argument.
So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end it becomes the result of reduce
.
Sounds complicated?
The easiest way to grasp that is by example.
Here we get a sum of an array in one line:
```js run let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((sum, current) => sum + current, 0);
alert(result); // 15 ```
The function passed to reduce
uses only 2 arguments, that’s typically enough.
Let’s see the details of what’s going on.
sum
is the initial
value (the last argument of reduce
), equals 0
, and current
is the first array element, equals 1
. So the function result is 1
.sum = 1
, we add the second array element (2
) to it and return.sum = 3
and we add one more element to it, and so on…The calculation flow:
Or in the form of a table, where each row represents a function call on the next array element:
sum |
current |
result | |
|---|---|---|---|
| the first call | 0 |
1 |
1 |
| the second call | 1 |
2 |
3 |
| the third call | 3 |
3 |
6 |
| the fourth call | 6 |
4 |
10 |
| the fifth call | 10 |
5 |
15 |
Here we can clearly see how the result of the previous call becomes the first argument of the next one.
We also can omit the initial value:
```js run let arr = [1, 2, 3, 4, 5];
// removed initial value from reduce (no 0) let result = arr.reduce((sum, current) => sum + current);
alert( result ); // 15 ```
The result is the same. That’s because if there’s no initial, then reduce
takes the first element of the array as the initial value and starts the iteration from the 2nd element.
The calculation table is the same as above, minus the first row.
But such use requires an extreme care. If the array is empty, then reduce
call without initial value gives an error.
Here’s an example:
```js run let arr = [];
// Error: Reduce of empty array with no initial value // if the initial value existed, reduce would return it for the empty arr. arr.reduce((sum, current) => sum + current); ```
So it’s advised to always specify the initial value.
The method arr.reduceRight does the same, but goes from right to left.
Arrays do not form a separate language type. They are based on objects.
So typeof
does not help to distinguish a plain object from an array:
js run alert(typeof {}); // object alert(typeof []); // same
…But arrays are used so often that there’s a special method for that: Array.isArray(value). It returns true
if the value
is an array, and false
otherwise.
```js run alert(Array.isArray({})); // false
alert(Array.isArray([])); // true ```
Almost all array methods that call functions – like find
, filter
, map
, with a notable exception of sort
, accept an optional additional parameter thisArg
.
That parameter is not explained in the sections above, because it’s rarely used. But for completeness we have to cover it.
Here’s the full syntax of these methods:
arr.find(func, thisArg);
arr.filter(func, thisArg);
arr.map(func, thisArg);
// ...
// thisArg is the optional last argument
The value of thisArg
parameter becomes this
for func
.
For example, here we use a method of army
object as a filter, and thisArg
passes the context:
```js run let army = { minAge: 18, maxAge: 27, canJoin(user) { return user.age >= this.minAge && user.age < this.maxAge; } };
let users = [ {age: 16}, {age: 20}, {age: 23}, {age: 30}];
! // find users, for who army.canJoin returns true let soldiers = users.filter(army.canJoin, army); /!
alert(soldiers.length); // 2 alert(soldiers[0].age); // 20 alert(soldiers[1].age); // 23 ```
If in the example above we used users.filter(army.canJoin)
, then army.canJoin
would be called as a standalone function, with this=undefined
, thus leading to an instant error.
A call to users.filter(army.canJoin, army)
can be replaced with users.filter(user => army.canJoin(user))
, that does the same. The latter is used more often, as it’s a bit easier to understand for most people.
A cheat sheet of array methods:
push(...items)
– adds items to the end,pop()
– extracts an item from the end,shift()
– extracts an item from the beginning,unshift(...items)
– adds items to the beginning.splice(pos, deleteCount, ...items)
– at index pos
deletes deleteCount
elements and inserts items
.slice(start, end)
– creates a new array, copies elements from index start
till end
(not inclusive) into it.concat(...items)
– returns a new array: copies all members of the current one and adds items
to it. If any of items
is an array, then its elements are taken.indexOf/lastIndexOf(item, pos)
– look for item
starting from position pos
, return the index or -1
if not found.includes(value)
– returns true
if the array has value
, otherwise false
.find/filter(func)
– filter elements through the function, return first/all values that make it return true
.findIndex
is like find
, but returns the index instead of a value.forEach(func)
– calls func
for every element, does not return anything.map(func)
– creates a new array from results of calling func
for every element.sort(func)
– sorts the array in-place, then returns it.reverse()
– reverses the array in-place, then returns it.split/join
– convert a string to array and back.reduce/reduceRight(func, initial)
– calculate a single value over the array by calling func
for each element and passing an intermediate result between the calls.Array.isArray(arr)
checks arr
for being an array.Please note that methods sort
, reverse
and splice
modify the array itself.
These methods are the most used ones, they cover 99% of use cases. But there are few others:
arr.some(fn)/arr.every(fn) check the array.
The function fn
is called on each element of the array similar to map
. If any/all results are true
, returns true
, otherwise false
.
These methods behave sort of like ||
and &&
operators: if fn
returns a truthy value, arr.some()
immediately returns true
and stops iterating over the rest of items; if fn
returns a falsy value, arr.every()
immediately returns false
and stops iterating over the rest of items as well.
We can use every
to compare arrays: ```js run function arraysEqual(arr1, arr2) { return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]); }
alert( arraysEqual([1, 2], [1, 2])); // true ```
arr.fill(value, start, end) – fills the array with repeating value
from index start
to end
.
arr.copyWithin(target, start, end) – copies its elements from position start
till position end
into itself, at position target
(overwrites existing).
arr.flat(depth)/arr.flatMap(fn) create a new flat array from a multidimensional array.
For the full list, see the manual.
From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that’s much easier.
Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods.
Afterwards whenever you need to do something with an array, and you don’t know how – come here, look at the cheat sheet and find the right method. Examples will help you to write it correctly. Soon you’ll automatically remember the methods, without specific efforts from your side.


Site Analysis
Total Sales
Total Sales
Total Usage
$5,032
$5,032 $1,055
$5,032 $1,055
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
Helpful?Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
Helpful?Allina D’croze
Lorem Ipsum is simply dummy text of the industry.
Monthly Profit
Today
Yesterday
Total Sales
Today
Yesterday


Ordinances shall be permanently filed by the city manager and shall be kept available for public inspection.


So easy to use, even your dog could do it.
We have all the dogs, the greatest dogs.
Find the love of your dog's life or your money back.
© Copyright 2021 TinDog


Matching Game
Flip all the cards to Win the Game.
Easy
Medium
Hard
Moves
Congratulations!
You have won.
Game Stats:
Stars:
Moves:
Time:
Replay


Recipe 1.3. Testing Whether an Object Is String-like
Credit: Luther
Blissett
Problem
You need to test if an object, typically an argument to a function or
method you're writing, is a string (or more
precisely, whether the object is string-like).
Solution
A simple
and fast way to check whether something is a string or Unicode object
is to use the built-ins isinstance and
basestring, as
follows:
def isAString(anobj):
return isinstance(anobj, basestring)
Discussion
The first approach to solving this recipe's problem
that comes to many programmers' minds is
type-testing:
def isExactlyAString(anobj):
return type(anobj) is type('')
However, this approach is pretty bad, as it willfully destroys one of
Python's greatest strengthssmooth,
signature-based polymorphism. This kind of test would reject Unicode
objects, instances of user-coded subclasses of
str, and instances of any user-coded type that is
meant to be "string-like".
Using the isinstance built-in function, as
recommended in this recipe's Solution, is much
better. The built-in type basestring exists
exactly to enable this approach. basestring is a
common base class for the str and
unicode types, and any string-like type that user
code might define should also subclass basestring,
just to make sure that such isinstance testing
works as intended. basestring is essentially an
"empty" type, just like
object, so no cost is involved in subclassing it.
Unfortunately, the canonical isinstance checking
fails to accept such clearly string-like objects as instances of the
UserString class from Python Standard Library
module UserString, since that class, alas, does
not inherit from basestring.
If you need to support such types, you can check directly whether an
object behaves like a stringfor example:
def isStringLike(anobj):
try: anobj + ''
except: return False
else: return True
This isStringLike function is slower and more
complicated than the isAString function presented
in the "Solution", but it does
accept instances of UserString (and other
string-like types) as well as instances of str and
unicode.
The general
Python approach to type-checking is known as duck
typing: if it walks like a duck and quacks like a duck,
it's duck-like enough for our purposes. The
isStringLike function in this recipe goes only as
far as the quacks-like part, but that may be enough. If and when you
need to check for more string-like features of the object
anobj, it's easy to test a few
more properties by using a richer expression in the
TRy clausefor example, changing the clause
to:
try: anobj.lower( ) + anobj + ''
In my experience, however, the simple test shown in the
isStringLike function usually does what I need.
The
most Pythonic approach to type validation (or any validation task,
really) is just to try to perform whatever task you need to do,
detecting and handling any errors or exceptions that might result if
the situation is somehow invalidan approach known as
"it's easier to ask forgiveness
than permission" (EAFP).
try/except is the key tool in
enabling the EAFP style. Sometimes, as in this recipe, you may choose
some simple task, such as concatenation to the empty string, as a
stand-in for a much richer set of properties (such as, all the wealth
of operations and methods that string objects make available).
See Also
Documentation for the built-ins isinstance and
basestring in the Library
Reference and Python in a
Nutshell.
|


Visit the Eiffel Tower
This project was created for Day 3 of the #30DaysofCode Challenge. Because this is just a quick page that I threw together in a few hours for the challenge, it doesn't contain anywhere close to all of the information that is available for those who might be interested in visiting the Eiffel Tower.
You can find much more detailed information at the Office Eiffel Tower Site


des_two_stage
determines two-stage two-arm randomised clinical trial
designs, assuming the primary outcome variable is Bernoulli distributed. It
supports a flexible framework for specifying which scenarios to control the
type-I and type-II error-rates for, and allows for design determination
assuming a variety of test statistics. In all instances, des_two_stage
computes the optimal required sample size in each arm in each stage, the
associated optimal stopping boundaries, and returns information on key
operating characteristics.
des_two_stage(
type = "binomial",
alpha = 0.1,
beta = 0.2,
delta = 0.2,
ratio = 1,
Pi0 = 0.1,
Pi1 = Pi0[1],
nCmax = 50L,
equal = T,
w = c(1, 0, 0, 0, 0),
piO = Pi0[1],
efficacy = FALSE,
futility = TRUE,
efficacy_type = 0L,
efficacy_param = NULL,
futility_type = 1L,
futility_param = 0L,
summary = FALSE
)
Arguments
| type |
A character string indicating the chosen design
framework/test statistic to assume. Must be one of "barnard" ,
"binomial" , "fisher" , or "sat" . Defaults to
"binomial" . |
| alpha |
A numeric indicating the chosen value for
α, the significance level
(i.e., the type-I error-rate). Defaults to 0.1 . |
| beta |
A numeric indicating the chosen value for
β, used in the definition of
the desired power (i.e., the type-II error-rate). Defaults to 0.2 . |
| delta |
A numeric indicating the chosen value for
δ, the treatment effect
assumed in the power calculation. Defaults to 0.2 . |
| ratio |
A numeric indicating the chosen value for
r, the allocation ratio to
the experimental arm, relative to the control arm. Defaults to 1 . |
| Pi0 |
A numeric vector indicating the
chosen values of the control arm response rate to control the type-I
error-rate to level α for.
Must either be of length one, indicating a single point, or of
length two. In this case, the elements indicate the
range of possible response rates to allow for. Defaults to 0.1 . |
| Pi1 |
A numeric vector indicating the
chosen values of the control arm response rate to allow for in the power
calculations. Must either be of length one,
indicating a single point, or of length two. In this case, the
elements indicate the range of possible response rates to allow for. Defaults
to Pi0[1] . |
| nCmax |
A numeric indicating the maximum value of the
sample size in the control arm (across both stages) to consider in the search
procedure. Defaults to 50L . |
| equal |
A logical variable indicating whether the sample
size of the two stages should be equal. Defaults to TRUE . |
| w |
A numeric vector indicating the weights
to use in the optimality criteria. Must be of length five, with
all elements greater than or equal to zero, and at least one of the first
four elements strictly positive. Defaults to c(1, 0, 0, 0, 0) . |
| piO |
A numeric indicating the value of the control
arm response rate to assume in the optimality criteria. Defaults to
Pi0[1] . |
| efficacy |
Only used if type is one of "barnard" ,
"binomial" , or "sat" . Then, it is a
logical variable indicating whether to include early stopping
for efficacy in the design. Defaults to FALSE . |
| futility |
Only used if type is one of "barnard" ,
"binomial" , or "sat" . Then, it is a
logical variable indicating whether to include early stopping
for futility in the design. Defaults to TRUE . |
| efficacy_type |
Only used if type is "fisher" . Then, it is
a numeric indicating whether, and which type of, early stopping
for efficacy to include in the design. See the vignette for details. Defaults
to 0L . |
| efficacy_param |
Only used if type is "fisher" and
efficacy_type is not equal to 0L . Then, it is a
numeric that influences the precise way in which an efficacy
boundary is specified. See the vignette for details. Defaults to NULL . |
| futility_type |
Only used if type is "fisher" . Then, it is
a numeric indicating whether, and which type of, early stopping
for futility to include in the design. See the vignette for details. Defaults
to 1L . |
| futility_param |
Only used if type is "fisher" and
futility_type is not equal to 0L . Then, it is a
numeric that influences the precise way in which a futility
boundary is specified. See the vignette for details. Defaults to 1L . |
| summary |
A logical variable indicating whether a summary
of the function's progress should be printed to the console. Defaults to
FALSE . |
Value
A list
with additional class "ph2rand_des"
,
containing each of the input parameters along with several additional
variables, including
A list
in the slot $boundaries
giving the
rejection boundaries of the optimal design. The names of these elements
depends on the value of type
.
A tibble
in the slot $feasible
summarising the
operating characteristics of the feasible designs.
A numeric
vector
in the slot $nC
giving the sample sizes in the control arm in each stage for the optimal
design.
A numeric
vector
in the slot $nE
giving the sample sizes in the experimental arm in each stage for the optimal
design.
A tibble
in the slot $opchar
summarising the
operating characteristics of the optimal design.
See also
Examples


To create a successful design we first must learn about your company, your ideas, your plans and become an extension of your staff to allow us to create a product that is truly a statement about your company
Solving a visual problem, building a website or designing priinted materials is a collaboration and an educational experience. We use planning and iteration to illustrate the possibilities. We listen. Making the end product something you are completely satisfied with.
Pretty picturesCounterspace was founded because we love three things. Design, information and education.
When we design its not about pretty pictures. Its not about putting a pretty wrapper on technology. It’s about using design techniques to allow users to read and comprehend the content they are viewing. To get a picture in their mind of the entity they are visiting.
The internet is information. Who, what, where and how. We organize information so that your audience is able to be entertained, informed and educated.
Education and learning drives us. Education is the reason why people internet surf, whether they are looking for the best deals or researching a paper. We help you plan your content and web site experience so that your users will be educated and will keep coming back.
We have spent the last decade living and breathing multimedia. Timelines, games, applications you name it we have produced successful products across a wide range of platforms and industries.
We founded counterspace to enable us to utilize our expertise, have fun and deliver high end products to our clients. Without compromise. Without excuses.
Another design company?We grew up with the internet, we had fun, we experimented and we helped develop interactivity standards and influence thousands of people online. We understand the internet. It’s history and it’s future.
The internet changes weekly and while we do not proclaim that we know everything, we use our experience to solve new problems, learn new


Open this example on 2 different machines, (or browsers), then open the console, and you should see the same object being echoed on the last line of each browser, as the last loaded browser sets the value 2nd.


|
Portable Radio
|
Graphical User Interface. More...
#include <GUI.hpp>
Public Member Functions | |
| GUI (hwlib::window &window_part, hwlib::glcd_oled &display, KY040 &button, hwlib::terminal_from &stereoField, hwlib::window &signalWindow, hwlib::window &batteryWindow, hwlib::terminal_from &frequencyField, hwlib::terminal_from &menuField, hwlib::terminal_from &settingsField, hwlib::terminal_from &stationField) | |
| Constructor. More... | |
| void | receptionStrength (const unsigned int signalStrength) |
| Print Reception Strenght. More... | |
| void | batteryPercentage (const unsigned int voltage) |
| Print Battery Percentage. More... | |
| void | displayStereo (const bool stereo) |
| Display Stereo. More... | |
| void | displayStationName (const char &stationName) |
| Display Station Name. More... | |
| void | displayFrequency (const unsigned int frequency, const bool change) |
| Display Tuned Frequency. More... | |
| void | displayMenuArea (const unsigned int menuArea) |
| Display Menu. More... | |
| void | displayMenuUpdate (const unsigned int signalStrength, const float frequency, const bool change, const unsigned int voltage, const bool stereo, const unsigned int menuArea, Radio &radio, const bool showRadioDataStationName, const char *stationName, const bool curMute, const dateData &date, const bool force=false) |
| Update GUI. More... | |
| void | showSettings (KY040 &button, Radio &radio, unsigned int &menuArea) |
| Display Settings. More... | |
Graphical User Interface.
This is a class which makes it possible to display the entire GUI with the given values.
| GUI::GUI | ( | hwlib::window & | window, |
| hwlib::glcd_oled & | display, | ||
| KY040 & | button, | ||
| hwlib::terminal_from & | stereoField, | ||
| hwlib::window & | signalWindow, | ||
| hwlib::window & | batteryWindow, | ||
| hwlib::terminal_from & | frequencyField, | ||
| hwlib::terminal_from & | menuField, | ||
| hwlib::terminal_from & | settingsField, | ||
| hwlib::terminal_from & | stationField | ||
| ) |
Constructor.
This constructor has a lot of mandatory parameters. However, they all seem very logical when you look at the first part of the main.cpp from this application.
| void GUI::batteryPercentage | ( | const unsigned int | voltage | ) |
Print Battery Percentage.
This function calls print() from batteryBars.
| void GUI::displayFrequency | ( | const unsigned int | frequency, |
| const bool | change | ||
| ) |
Display Tuned Frequency.
This function prints the currently tuned frequency in the frequencyField.
| void GUI::displayMenuArea | ( | const unsigned int | menuArea | ) |
Display Menu.
This function prints the current menu the user is in; can be one of auto, manual or presets.
| void GUI::displayMenuUpdate | ( | const unsigned int | signalStrength, |
| const float | frequency, | ||
| const bool | change, | ||
| const unsigned int | voltage, | ||
| const bool | stereo, | ||
| const unsigned int | menuArea, | ||
| Radio & | radio, | ||
| const bool | showRadioDataStationName, | ||
| const char * | stationName, | ||
| const bool | curMute, | ||
| const dateData & | date, | ||
| const bool | force = false |
||
| ) |
Update GUI.
This function updates all values that have changed.
| void GUI::displayStationName | ( | const char & | stationName | ) |
Display Station Name.
This function prints the given station name in the textArea field and then also prints the signalindicator since this could have changed after retrieving RDS station Name.
| void GUI::displayStereo | ( | const bool | stereo | ) |
Display Stereo.
This function prints "ST" or "MN" when respectively stereo or mono signal is received . It prints this in the given StereoField.
| void GUI::receptionStrength | ( | const unsigned int | signalStrength | ) |
Print Reception Strenght.
This function calls print() from signalBars.


test module¶
-
test.
load_multi_model
(multi_args, model_args, data_args, gpu_ids)¶ Load multi lodel (a frontal model and a lateral model).
-
test.
test
(args)¶ Run testing with the given args.
- The function consists of the following steps:
- Get model for evaluation.
- Get task sequence and class weights.
- Get data eval loaders and evaluator.
- Evaluate and save model performance (metrics and curves).
-
test.
write_results
(dataset_name, split, eval_metrics, metrics, output_path, name, ckpt_info)¶ Write model performance to a CSV file.


(To unload the current widget(s), just refresh the page)
Enter url of template of the widget to test:
Enter class of widget template:
Load Widget


PHOTOS: Deepika Padukone and Ranveer Singh return to the bay after their spiritual first wedding anniversary celebration
by TIMESOFINDIA.COMDeepika Padukone and Ranveer Singh are back to the bay after spiritually celebrating their first wedding anniversary. The couple completed their one year of togetherness on November 14.
Just a few minutes ago the couple was papped at the Mumbai airport along with their families. In the photos both the actors are seen wearing in the same outfits which they had donned at the Golden Temple. Deepika looked stunning in a maroon, heavily embroidered dress while Ranveer looked dapper in a floral ethnic suit with Nehru jacket. The power couple happily posed for the shutterbugs along with their families as they walked out of the airport.
Check out the photos:
On Wednesday the duo had jetted off to Andra Pradesh along with respective families. Yesterday, DeepVeer visited the Tirupati Balaji Temple and Padmavati temple. Later in the evening, they headed to Amritsar and today in the wee hours of the morning they offered their prayers at Golden Temple.
Deepika and Ranveer tied the knot in a private affair at Lake Como last year, post which the couple hosted several receptions in India.


brain_diffusion.histogram_utils
¶
brain_diffusion.histogram_utils
¶
-
brain_diffusion.histogram_utils.
histogram_by_video
(SMfilename, xlabel='Log Diffusion Coefficient Dist', ylabel='Trajectory Count', fps=100.02, y_range=5000, frame_range=range(5, 30, 5), analysis='log', theta='D')[source]¶ Plots a histogram of mean squared displacements or diffusion coefficients from input data.
- SMfilename : string
- Filename of particle MSDs. Must be a csv file, comma delimited. Must be organized as frames x particles.
- xlabel : string
- X label of the output graph.
- ylabel : string
- Y label of the output graph.
- fps : float or int
- The frame rate of the video being analyzed. Only required if graphing diffusion coefficients rather than mean squared displacements.
- y_range : int
- Y range of the output graph.
- frame_range : range
- Range containing which frames the user wishes to be plotted.
- analysis : string
- Desired type of data to be plotted. If input is ‘log’, plots the natural logarithm of the data. Any other input will plot the raw input data.
- theta : string
- Desired type of data to be plotted. If input is ‘D’, plots diffusion coefficients. Any other input will plot the mean squared displacements.
Returns ‘Graph completed successfully’ if function is successful.
>>> nframe = 51 >>> npar = 1000 >>> SMxy = np.zeros((nframe, npar)) >>> for frame in range(0, nframe): SMxy[frame, :] = np.random.normal(loc=0.5*frame, scale=0.5, size=npar) >>> np.savetxt('sample_file.csv', SMxy, delimiter=',') >>> histogram_by_video('sample_file.csv', y_range=500, analysis="nlog", theta="MSD") >>> os.remove('sample_file.csv') >>> os.remove('sample_file_hist.png')


Using the concept of standing waves in a Ruben's Tube - a large tube sealed at both ends, one of which is connected to a speaker. The tube has many tiny holes, and when standing waves are created in the ignited propane pumped into the tube, there is variation in pressure and we see the same waves in the flames. The Pyro Board extends this concept to 2 dimensions.
The Zeusaphone is a variety of solid state tesla coil that has been modified to produce musical tones by modulating its spark output. The musical tone results directly from the passage of the spark through the air.
LiDAR (Light Detection and Ranging) is a concept closely related to RADAR and SONAR, and works by illuminating targets using light. It measures the distance to a target by measuring the reflected light with a sensor, and is able to detect most of the features as seen by the camera along with the exact distance of where that point is.
Using the concept of Microphone Arrays and Mircophone Steering to focus towards a given direction/source of sound while also eliminating all ambient sounds and noise, Acoustic Beamforming aims to personalize sound itself. From Voice Tracking to Acoustic Cameras, it has many potential future applications.
Building a computerized telescope Star Tracker, which would be configured to Stellarium, a sky-viewing software. This will help in easily spotting low-intensity objects in the sky.
Microbial Fuel Cells are devices that use bacteria as the catalysts to oxidize organic and inorganic matter and generate current. Thusly they can be used for detecting bacteria, and signs of life, possibly even on other planets.
A CanSat is a type of sounding rocket payload used to teach space technology. In CanSat competitions, the payload is required to fit inside the volume of a typical soda can, and have a mass below 350g. We're building a telemetry CanSat to collect and transmit data from the flight and weather conditions in real time.
A Comet's dust particles can vary in size anywhere between a few microns long to a few cm long, and when the comet trails containing these particles intersect the orbits of a planet they can create storms, and these meteor impacts can inflict serious damage to spacecrafts in its path. However, using precise models we can predict the path these dust particles follow - hence avoid collisions! This is exactly what we're trying to do in this project.


Navigation
index
next
|
previous
|
Delta Modeling Section
|
GitHub
|
Search
|
Learning Resources for Bay-Delta SCHISM
»
Bay-Delta SCHISM Topical Guide
»
Key Run Parameters and Gotchas
Table of Contents
Key Run Parameters and Gotchas
Runtime settings
Hotstart settings
Nudging settings
Output requests
Settings that have historically gone awry
What happens when SCHISM versions get advanced?
Previous topic
From Barotropic to Baroclinic
Next topic
Run Initialization and Restart (Hotstart)
This Page
Show Source
Quick search
Key Run Parameters and Gotchas
¶
Runtime settings
¶
Hotstart settings
¶
Nudging settings
¶
Output requests
¶
Settings that have historically gone awry
¶
What happens when SCHISM versions get advanced?
¶
Navigation
index
next
|
previous
|
Delta Modeling Section
|
GitHub
|
Search
|
Learning Resources for Bay-Delta SCHISM
»
Bay-Delta SCHISM Topical Guide
»
Key Run Parameters and Gotchas


A Breed Apart (Reviewed on Aug. 19th/98)
Starring Rutger Hauer, Powers Boothe, Kathleen Turner
"A Breed Apart" casts Rutger Hauer as a crazy, bird-loving recluse who picks his feathered friends over Kathleen Turner. A bit hard to swallow? That's only the first of many improbabilities in this film.
Hauer stars as a man obsessed with keeping the birds on his island safe, while Boothe plays a guy hired to steal a couple of rare eagle eggs by a rich egg collector. Turner is the woman caught between the two men.
"A Breed Apart" isn't a bad movie, exactly. Indeed, I found myself rooting for both the Hauer and Boothe characters, even though their goals couldn't be more different. The problem with the film is that there are just too many inconsistencies. For example, early on in the film, Hauer physically assaults two drunken rednecks shooting at "his" birds. Later on, the rednecks come back for revenge with four other people, and Hauer kills a few of them. I have a tough time believing that the police wouldn't get involved at that point.
Another problem is the silly love-triangle that develops. I didn't care one way or the other who ended up with Turner. I was more interested in finding out which of the two men would be victorious in their respective missions. However, despite this uninteresting sub-plot, Turner did manage to give a great performance as the woman who reminds the two men that sometimes there's more to life than money and birds.
As for Hauer, he's an actor I've always admired. He has a penchant for picking strange and unusual characters. And this one is no exception. He's frequently seen riding around his island on a white horse, wearing pirate's clothing, and holstering a cross-bow. Despite all his eccentric mannerisms, though, Hauer always manages to let the human side of his character shine through. For example, there's a scene in which he barks at Turner and her son because they came onto his island a day early. He comes off as crazy loner in that scene, but a few minutes later, he is apologizing to Turner, and we believe his intentions.
"A Breed Apart" isn't a great movie by any means, but it does contain good performances by all three leads, and it's worth seeing for that reason alone.
*** out of ****
Dave "Loopy" Nusair<EMAIL_ADDRESS>; "The Artist Formally Known As Prince is now going by just The Artist. ; : Despite this, I will still refer to him as The Fruit." : ; -Norm MacDonald ;
Dept. of Good Vibes, Come visit my Reel Film Reviews site Carleton University at "http://chat.carleton.ca/~dnusair"
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


=== Test case: lasp_SUITE:contracted_latency_test/1 (click for source code)
=== Config value:
[{watchdog,<0.450.0>},
<EMAIL_ADDRESS>{tc_group_properties,[]},
{tc_group_path,[]},
{data_dir,"/Users/anne-francevanswieten/lasp/_build/test/lib/lasp/test/lasp_SUITE_data/"},
<EMAIL_ADDRESS>=== Current directory is<EMAIL_ADDRESS>=== Started at 2017-04-18 15:38:40
*** User 2017-04-18 15:38:40.828 ***
Beginning case: contracted_latency_test
*** User 2017-04-18 15:38:40.846 ***
15:38:40.846 [info] Configured peer_service_manager partisan_default_peer_service_manager on node runner@MBPdeAnneFrance
*** User 2017-04-18 15:38:42.153 ***
15:38:42.153 [info] Enabling membership...
*** User 2017-04-18 15:38:42.154 ***
15:38:42.154 [info] Disabling blocking sync...
*** User 2017-04-18 15:38:42.159 ***
15:38:42.158 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-1@MBPdeAnneFrance'
*** User 2017-04-18 15:38:43.651 ***
15:38:43.651 [info] Enabling membership...
*** User 2017-04-18 15:38:43.653 ***
15:38:43.653 [info] Disabling blocking sync...
*** User 2017-04-18 15:38:43.657 ***
15:38:43.657 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-2@MBPdeAnneFrance'
*** User 2017-04-18 15:38:45.136 ***
15:38:45.136 [info] Enabling membership...
*** User 2017-04-18 15:38:45.139 ***
15:38:45.139 [info] Disabling blocking sync...
*** User 2017-04-18 15:38:45.145 ***
15:38:45.145 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-3@MBPdeAnneFrance'
*** User 2017-04-18 15:38:45.380 ***
Joining node: 'node-3@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52429
*** User 2017-04-18 15:38:45.385 ***
Joining issued: 'node-3@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52429
*** User 2017-04-18 15:38:45.385 ***
Joining node: 'node-2@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52414
*** User 2017-04-18 15:38:45.386 ***
Joining issued: 'node-2@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52414
*** User 2017-04-18 15:38:45.387 ***
Joining node: 'node-1@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52403
*** User 2017-04-18 15:38:45.387 ***
Joining issued: 'node-1@MBPdeAnneFrance' to runner@MBPdeAnneFrance at port 52403
*** User 2017-04-18 15:38:45.449 ***
Waiting for join to complete with manager: partisan_default_peer_service_manager
*** User 2017-04-18 15:38:45.450 ***
Finished.
*** CT 2017-04-18 15:38:45.464 *** COVER INFO
Adding nodes to cover test: [runner@MBPdeAnneFrance]
*** CT 2017-04-18 15:38:45.472 *** COVER INFO
Successfully added nodes to cover test: []
*** User 2017-04-18 15:38:45.472 ***
Case finished: contracted_latency_test
*** User 2017-04-18 15:38:52.518 ***
15:38:52.518 [info] Application lasp exited with reason: stopped
=== Ended at 2017-04-18 15:38:52
=== successfully completed test case
=== Returned value: ok
Test run history
| Top level test index


Namespace PacManBot.Games
Classes
BaseGame
The base all games inherit from. Implements IBaseGame.
Board<T>
Wrapper for a 2D array that introduces index looping, and allows access using Pos coordinates.
ChannelGame
A type of game that takes place in a specific channel. Implements IChannelGame.
MultiplayerGame
A specialized type of game that is channel-based and allows for inter-player mechanics as well as AI. Implements IMultiplayerGame.
Instances of its subclasses must be created using CreateNewAsync<TGame>(UInt64, SocketUser[], IServiceProvider).
Structs
Player
Represents the index of the user in a IMultiplayerGame. Acts as a wrapper for System.Int32, like an enum.
Pos
A position in a Board<T>, expressed as x and y coordinates.
Interfaces
IBaseGame
The interface all games derive from.
IChannelGame
The interface for channel-specific games, giving access to channel, guild and message members.
IMessagesGame
The interface for IChannelGames that receive message input.
IMultiplayerGame
The interface for multiplayer games, giving access to player and AI members.
IReactionsGame
The interface for IChannelGames that receive reaction input.
IStoreableGame
Identifies a game type as storeable, allowing calls to SaveAsync(IStoreableGame) and automatically deserializing stored instances that match the FilenameKey on start-up.
IUserGame
The interface for user-specific games. Has prevalence over IChannelGame when sorting between the two.
Enums
Dir
The four cardinal directions, useful with Pos and extension methods.
GameState
Indicates whether a game is ongoing, or why it ended.


JavaScript URI functions – unit tests
JavaScript/JScript/ECMAScript must be available and enabled in your web browser.


Mahaperiyava initiated many laudable activities to encourage Veda rakshanam and Go rakshanam. Sri Veda Moorthy Chandrashekarendra Saraswati Charitable Trust (SVMCSCT) is a not-for-profit organization registered as public charitable trust and it has reputed professionals as trustees having respected standing in the society. The trust has been formed to encourage and support veda patashalas, Go-shalas aross south India. Our aim is to help them as much as possible by honoring students, adhyapakas and support daily chores. The trust also extends financial support to marriage, educational and medical needs of the poor and needy.
Contribute to this noble cause: Contribute


Toggle navigation
Shirin's playgRound
About me
Archive
Categories
Feeds
Tags
Submit
Archive
2017
November
November 2, 2017
»
Explore Predictive Maintenance with flexdashboard
September
September 28, 2017
»
Blockchain & distributed ML - my report from the data2day conference
September 20, 2017
»
From Biology to Industry. A Blogger’s Journey to Data Science.
September 19, 2017
»
Why I use R for Data Science - An Ode to R
September 14, 2017
»
Moving my blog to blogdown
September 6, 2017
»
Data Science for Fraud Detection
September 4, 2017
»
Migrating from GitHub to GitLab with RStudio (Tutorial)
July
July 28, 2017
»
Social Network Analysis and Topic Modeling of codecentric’s Twitter friends and followers
July 17, 2017
»
How to do Optical Character Recognition (OCR) of non-English documents in R using Tesseract?
June
June 28, 2017
»
Characterizing Twitter followers with tidytext
June 13, 2017
»
Data Science for Business - Time Series Forecasting Part 3: Forecasting with Facebook's Prophet
June 9, 2017
»
Data Science for Business - Time Series Forecasting Part 2: Forecasting with timekit
May
May 28, 2017
»
Data Science for Business - Time Series Forecasting Part 1: EDA & Data Preparation
May 20, 2017
»
New R Users group in Münster!
May 15, 2017
»
Network analysis of Game of Thrones family ties
May 2, 2017
»
Update to autoencoders and anomaly detection with machine learning in fraud analytics
May 1, 2017
»
Autoencoders and anomaly detection with machine learning in fraud analytics
April
April 23, 2017
»
Does money buy happiness after all? Machine Learning with One Rule
April 23, 2017
»
Explaining complex machine learning models with LIME
April 16, 2017
»
Happy EasteR: Plotting hare populations in Germany
April 9, 2017
»
Data on tour: Plotting 3D maps and location tracks
April 2, 2017
»
Dealing with unbalanced data in machine learning
March
March 31, 2017
»
Building meaningful machine learning models for disease prediction
March 16, 2017
»
Plotting trees from Random Forest models with ggraph
March 7, 2017
»
Hyper-parameter Tuning with Grid Search for Deep Learning
February
February 27, 2017
»
Building deep neural nets with h2o and rsparkling that predict arrhythmia of the heart
February 19, 2017
»
Predicting food preferences with sparklyr (machine learning)
February 12, 2017
»
Conditional ggplot2 geoms in functions (QTL plots)
February 6, 2017
»
Scratching the Surface of Gender Biases
January
January 30, 2017
»
New features in World Gender Statistics app
January 29, 2017
»
Exploring World Gender Statistics with Shiny
January 22, 2017
»
R vs Python - a One-on-One Comparison
January 15, 2017
»
Feature Selection in Machine Learning (Breast Cancer Datasets)
January 5, 2017
»
Gene homology Part 3 - Visualizing Gene Ontology of Conserved Genes
2016
December
December 30, 2016
»
How to map your Google location history with R
December 22, 2016
»
Animating Plots of Beer Ingredients and Sin Taxes over Time
December 18, 2016
»
How to build a Shiny app for disease- & trait-associated locations of the human genome
December 14, 2016
»
Gene homology Part 2 - creating directed networks with igraph
December 11, 2016
»
Creating a network of human gene homology with R and D3
December 4, 2016
»
How to set up your own R blog with Github pages and Jekyll Bootstrap
December 2, 2016
»
Extreme Gradient Boosting and Preprocessing in Machine Learning - Addendum to predicting flu outcome with R
November
November 27, 2016
»
Can we predict flu deaths with Machine Learning and R?
November 20, 2016
»
Analysing the Gilmore Girls' coffee addiction with R
November 13, 2016
»
Creating a Gilmore Girls character network with R
November 6, 2016
»
Is 'Yeah' Josh and Chuck's favorite word?
November 1, 2016
»
Exploring the human genome (Part 2) - Transcripts
October
October 23, 2016
»
Exploring the human genome (Part 1) - Gene Annotations
October 16, 2016
»
USA/ Canada Roadtrip 2016
September
September 29, 2016
»
DESeq2 Course Work
September 28, 2016
»
exprAnalysis package


{% extends "general/base.html" %} {% set active_page = "resources" -%} {% set title = "Previous Versions | MITRE ATT&CK™" -%} {% set parsed = page.data | from_json %} {% block content %} {{ super () }}
We preserve previous versions of the website each time we do a major ATT&CK content update. Click below to see a previous version of the site or the updates that occurred with that particular major release.


--- layout: default ---
We are a research group at the Human-Computer Interaction Institute at Carnegie Mellon University. Our mission is to empower people to analyze and communicate data with interactive systems. Learn more
Our group conducts research in computer science at the intersection of human computer interaction, machine learning, data science, programming languages, and data management.
Visualization leverages human perception to make (potentially large) data accessible. We are developing new languages and tools for analysis and communication.
While computers can help us manage data, human judgment and domain expertise is what turns it into understanding. Meeting the challenges of increasingly large and complex data requires methods that richly integrate the capabilities of both people and machines.
machine learning models are part of larger applications. To develop meaningful experiences, we need to design models in the context of their intended use. We provide insights into models with interpretable machine learning. We work to unerstand and optimize the lifecycle of data and models.
🚧 Work in Progress 🚧


Growing up, my family kept a notecard in the kitchen that served as our grocery list. As time passed (and we needed to shop at more stores), more notecards were added to the stack. It was simple, but it worked. These times, however, demand a more technical solution to this age-old problem.
Getting married provided the impetus to find a solution. My wife and I both lead busy careers and on-the-go lifestyles; we needed a solution that would allow us to quickly access our grocery lists, adjust items in those lists, and go shopping when the opportunity struck.
TL;DR
Thanks to Trello, Launch Center Pro, Pythonista, and IFTTT, I have a simple, automated method for easily adding new grocery items to my lists (no matter where I am).
Managing the Lists in Trello
We examined many tools in our quest to find something suitable for grocery list management: Reminders, Clear, and many others. Although perfectly good apps, they failed to meet our criteria. Our ideal app should:
- be able to create an unlimited amount lists.
- allow for easy sharing of those lists between multiple individuals.
- be cross-platform and web-accessible.
- have a companion mobile app with a robust URL scheme.
- have a published API.
As we researched, one app kept coming up again and again: Trello. A longstanding member of my toolkit, Trello appeared to fit all of our needs: it wasn’t tied to any one platform, had a robust iOS app, was easy to for multiple users to use, etc. “Grocery management” wasn’t specifically advertised as a use for Trello, but with more and more thought, it stuck out as a clear choice.
We don’t get particularly fancy with our Trello setup. We merely create a list for every grocery store that we need and under it, we stack our items as cards:
This setup is simple and easy to support. Either of us can add new items as needed and, when shopping, can merely swipe away cards via the iOS app:
There’s only one “downside” to the Trello iOS app: adding items to it isn’t as quick as we’d like. From opening the app to adding an item, there are anywhere from 3-5 touches; it isn’t the biggest drawback, but it provides enough friction to be noticeable.
To fix this particular issue, I turned to an old friend.
Quick Entry via Launch Center Pro
In late May, Trello introduced a URL scheme for its iOS app. When this occurred, one app immediately popped to mind: Launch Center Pro. All sorts of automated Trello actions became possible by using LCP’s ability to “speak” with Trello. My first task was to cut the friction; I wanted the ability to quickly add grocery items to my various lists without having to dig and drag in the Trello app. Fortunately, Trello’s URL scheme documentation provided an exact mechanism to do this:
trello://x-callback-url/createCard?shortlink={board_shortlink}&list-id={list_id}&name=MyCardName&description=MyCardDescription
There are several key parts to this scheme:
Board Shortlink
: this is the unique identifier of the board (in my case, “Groceries and Household”). This can be found by looking the board’s URL.List ID
: this is the unique identifier of the list that will receive the new card (if omitted, the card gets added to the first list). More on this in a moment.Name
: the name of the card to be added.Description
: the description of the card to be added.
Knowing this, I constructed the following URL for use in LCP:
trello://x-callback-url/createCard?shortlink={MY-BOARD-SHORTLINK}&name=[prompt:Item]&list-id=[list:Grocery Stores|Vitamin Cottage=xxxx1234|Costco=xxxx1234|Target=xxxx1234|VitaCost=xxxx1234|Pharmaca=xxxx1234|Home Depot=xxxx1234]&x-success=
This is fairly straightforward. First, the action asks the user to input the name of the item:
Then, the user is prompted to pick the list to add to:
Once a list is chosen, the new card is added to the appropriate list in Trello:
Easy enough, yes, but I’ve skipped over one crucial piece of information: where did I get the unique IDs for the lists?
Sadly, finding these IDs is not as easy as finding the board’s short code; it involves opening the right-hand menu, selecting Share, Print, and Export...
and selecting Export JSON
. From here, you have to dig through the board’s JSON, which is filled with all the cards, checklists, etc., archived or open, that the board has (and all their associated metadata). It’s not the most pleasant process.
When I first created my “Groceries” action in LCP, I did all that manual work. Over time, however, my wife and I began to add new stores to the list; this necessitated more trips into the weeds of Trello’s JSON and the unpleasantness grew.
There had to be a better way.
List Creation via Pythonista
In the beginning of 2014, Phil Gruneich published a blog post on updating Launch Center Pro’s list with a user’s most-used Pinboard tags:
One of the coolest tricks from Launch Center Pro 2 is the [list] parameter, which allows you to create a prompt of options to pick. It’s great because services with a specific set of search queries doesn’t rely on your memory to be called, like your Pinboard tags. However, once in a while you must review and manually update your LCP’s lists and that’s a bummer, so I built a Pythonista script to update your Pinboard tags for you.
My mind began working; what would happen if I could take the same principle – of grabbing Trello data via its API – and use Pythonista to automatically build an LCP workflow?
Turns out, I could. This is what I ended up with:
Before this script will work for you, you will need to fill the two variables at the top of the script:
TRELLO_KEY
: your Trello developer key (generated from https://trello.com/1/appKey/generate)BOARD_SHORTCODE
: the short code of the board that has the grocery lists
To see what this script does, let’s look at some screenshots. First, Pythonista’s web browser opens and prompts me to authorize access to my Trello account:
Once authorized, Trello will offer up a token, which, once saved, will allow the Pythonista script to reach Trello’s API:
I copy the token and close the web browser. Upon returning to the Pythonista console, I paste the token and touch Return
. After a few brief seconds, Pythonista kicks me over to LCP, wherein I am presented with a new incoming action:
I merely tap on my existing “Groceries” action and replace it with this new iteration:
This solution is almost perfect, but one item continued to nag me: would I really have to manually run this Pythonista script every so often (to grab my list changes)?
Automation via IFTTT
With this particular workflow, it quickly became clear that I could automatically remind myself to run the Pythonista script every month via an IFTTT recipe:
When this recipe runs, I receive a notification on my phone; touching that notification automatically runs the Pythonista script:
Closing Thoughts
This is yet another case where a trusty, reliable set of automation tools allowed me to create a workflow that is beneficial and time-saving. Especially exciting is Phil’s concept of using Pythonista to talk to outside web services; I’m already off and running on ideas for other such workflows.
Isn’t this fun?


{{email_config.title}}
check_circle
The access request for {{email}} was approved and an email notification was sent.
You may now close this window.
{% extends "base.html" %} {% block main %}
The access request for {{email}} was approved and an email notification was sent.
You may now close this window.


The Keene Amateur Astronomers Club is a group of people whose goal is the enhancement of Amateur Astronomy by education, fellowship, sharing knowledge and enjoyment of the hobby. The KAA Club provides outreach programs paticularly with the Keene public library and holds monthly viewing sessions at our own observatory. Regular monthly club meetings are held at the Keene State college. Anyone interested is invited to attend. Our membership is open to students, parents, beginners, backyard amateurs and also experienced professionals. And we provide opportunities for our members to grow in one of the greatest hobbies in this world or any other! Founded in 1957, our club has a long and distinguished history and is a non-profit corporation registered with the State of New Hampshire. We are also members of the Astronomical League and participate in the annual Stellafane Convention which is consistently rated as one of America’s top Star Parties.
The February 2016 business meeting will take place on Friday the 12th at 7:00pm in the Young Student Center at KSC. Angel Rosario will continue his program on the Astronomical League's Constellation Hunter Program featuring this month the constellations: Orion, Camelopardalis, and Taurus. Observing, weather permitting, will occur following the meeting at the club's Observatory.
Observing will also take place Saturday, the 13th, beginning at 6:00pm at the club Observatory, weather permitting.
All members and interested non-members are invited. Contact the club Secretary for directions.
So you have a basic need to find out the latest discoveries and theories concerning the vast area above you? Well, look no further. Check out these websites to start your search:
When you read Astronomy or Sky & Telescope magazine, you will find short news articles clipped from journals. For in-depth information on articles, try Phys.org. And if your favorite space news website is not here, just let us know.
Winter began with the winter solstice which occurred on December 21st in the Northern Hemisphere and ends on March 20th at the spring equinox. The winter constellations are the 12 constellations that fall between 6 hours and 12 hours Right Ascension. Here are several resources to help you in your viewing during the coming months.
The American Association of Amateur Astronomers provides a list of the 12 winter constellations and a detailed map of the sky. They also provide similar information for the other seasons.
StarrySkies.com also has a nice interactive map of the stars of autumn/winter.
For greater details on the sky's wonders, move your fingers over to the star website at the University of Illinois at Urbana Champaign. Or check out the details of the constellations and their stars at the University of Wisconsin - Madison.
Are you looking to download a star chart or constellation map app for your smartphone or tablet computer? Here is an excellent article on available resources to guide you in your autumn/winter nighttime viewing. Some of these programs even allow you to hold your phoor tablet up to the night sky and see the exact position of the conne stellations. And, of course, trip over to eHow for identification tips. Pretty nifty!
SkyMaps. And be sure to check out what objects are visible this month for many of the Astronomical League Clubs at "What's Up Doc?", compliments of Dr. Aaron B. Clevenson. Then turn on your printer.
Visit Heavens Above and input your observing site coordinates. Check for sighting information on the International Space Station and on the Iridium satellites.
The left photo below was taken at a recent star party at the Keene observatory with members from SoVerA, KAA, and the KSC CALL program. The photo on the right is is a shot of the inside the observatory with members Jim Faux, Phinie Faux, and Bob Taylor. Both photos were taken by Claudio Veliz, SoVerA/KAA.
The above image of our moon was photographed by Jim Faux on September 25, 2009 at 6:42 pm in North Truro, MA as a jet was lifting off from Logan Airport. The image was taken with a handheld Canon 20D. [1/20 sec, F5.6, ISO-200, 300MM]


Attention
This tutorial is work in progress. Take a look at the arrows.py example file in Examples for fully working code for the arrows.
This tutorial will explain one way to make arrows/sticky projectiles that can stick on the target.
The tutorial is heavily inspired by the Box2d tutorial “Box2D C++ tutorials - Sticky projectiles” found here http://www.iforce2d.net/b2dtut/sticky-projectiles (but adjusted for python, pymunk and chipmunk).
For this tutorial you will need to know some pymunk basics. I recommend that you read the other tutorial(s) and try out easier examples first before you continue.
Except for pymunk you will also need pygame to follow this tutorial. However, it should be no problem to use another graphics and input library if you want, for example pyglet.
We will try to accomplish
In the end we should have a cannon like object shooting arrows that flies in a believable way and sticks to objects if they hit hard enough.
Before we start with the arrow we need a scene to contain it and a “cannon” that can aim:
import sys
import pygame
from pygame.locals import *
from pygame.color import *
import pymunk
from pymunk.vec2d import Vec2d
from pymunk.pygame_draw import draw_space, from_pygame
width = height = 600
def main():
### PyGame init
pygame.init()
screen = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()
running = True
font = pygame.font.SysFont("Arial", 16)
### Physics stuff
space = pymunk.Space()
# walls - the left-top-right-bottom walls
static_lines = [pymunk.Segment(space.static_body, (50, 50), (50, 550), 5)
,pymunk.Segment(space.static_body, (50, 550), (550, 550), 5)
,pymunk.Segment(space.static_body, (550, 550), (550, 50), 5)
,pymunk.Segment(space.static_body, (50, 50), (550, 50), 5)
]
space.add_static(static_lines)
### "Cannon" that can fire arrows
cannon_body = pymunk.Body()
player_shape = pymunk.Circle(cannon_body, 25)
cannon_body.position = 100,100
space.add(player_shape)
while running:
for event in pygame.event.get():
if event.type == QUIT or \
event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
running = False
mpos = pygame.mouse.get_pos()
p = from_pygame( Vec2d(mpos), screen )
mouse_position = p
cannon_body.angle = (mouse_position - cannon_body.position).angle
### Clear screen
screen.fill(pygame.color.THECOLORS["black"])
### Draw stuff
draw_space(screen, space)
### Update physics
fps = 60
dt = 1./fps
space.step(dt)
### Info and flip screen
screen.blit(font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]), (0,0))
screen.blit(font.render("Aim with mouse, click to fire", 1, THECOLORS["darkgrey"]), (5,height - 35))
screen.blit(font.render("Press R to reset, ESC or Q to quit", 1, THECOLORS["darkgrey"]), (5,height - 20))
pygame.display.flip()
clock.tick(fps)
if __name__ == '__main__':
sys.exit(main())


Elastic Load Balancing Listener Certificate
The Certificate
property type specifies the default SSL server certificate that Elastic Load Balancing
will deploy on an listener.
For more information, see Create an HTTPS Listener for Your Application Load Balancer in the Application Load Balancers Guide.
The Certificates
property of the AWS::ElasticLoadBalancingV2::Listener resource contains a list of one Certificate
property type.
Syntax
JSON
{ "CertificateArn" :
String
}
YAML
CertificateArn:
String


Login
Login with Email and Password
Create Account
Display Name
Email Address
Password
visibility
visibility_off
Forgot Password
- OR -
Don't have an account yet?
Register
Already have an account?
Login


8 references to RaiseCloseCompleted
System.Management.Automation (8)
engine\remoting\fanin\OutOfProcTransportManager.cs (4)
576
RaiseCloseCompleted
();
602
RaiseCloseCompleted
();
692
RaiseCloseCompleted
();
2424
RaiseCloseCompleted
();
engine\remoting\fanin\WSManTransportManager.cs (4)
1230
RaiseCloseCompleted
();
2023
sessionTM.
RaiseCloseCompleted
();
3180
RaiseCloseCompleted
();
3593
cmdTM.
RaiseCloseCompleted
();