In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).
In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files
function from the scikit-learn library:
train_files
, valid_files
, test_files
- numpy arrays containing file paths to imagestrain_targets
, valid_targets
, test_targets
- numpy arrays containing onehot-encoded classification labels dog_names
- list of string-valued dog breed names for translating labelsfrom sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob
# define function to load train, test, and validation datasets
def load_dataset(path):
data = load_files(path)
dog_files = np.array(data['filenames'])
dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
return dog_files, dog_targets
# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]
# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files
.
import random
random.seed(8675309)
# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)
# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades
directory.
In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image
img = cv2.imread(human_files[88])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale
function executes the classifier stored in face_cascade
and takes the grayscale image as a parameter.
In the above code, faces
is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x
and y
) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w
and h
) specify the width and height of the box.
We can use this procedure to write a function that returns True
if a human face is detected in an image and False
otherwise. This function, aptly named face_detector
, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector
function.
human_files
have a detected human face? dog_files
have a detected human face?  You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short
and dog_files_short
.
Answer:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
## TODO: Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
humans_detected_as_human_list= [1 if face_detector(human) else 0 for human in human_files_short ]
dogs_detected_as_human_list =[1 if face_detector(dog) else 0 for dog in dog_files_short ]
humans_detected_as_human_count = sum(humans_detected_as_human_list)
dogs_detected_as_human_count = sum(dogs_detected_as_human_list)
print("Detected {} humans in human files of total {} , ratio: {}".format(humans_detected_as_human_count,len(human_files_short),humans_detected_as_human_count/len(human_files_short) ) )
print("Detected {} humans in dog files of total {} , ratio: {}".format(dogs_detected_as_human_count,len(dog_files_short),dogs_detected_as_human_count/len(dog_files_short) ) )
##Show dogs detected as human
for i,v in enumerate(dogs_detected_as_human_list):
if v == 1:
img = cv2.imread(dog_files_short[i])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?
Answer: Clear view of face is required to properly detect humans or dogs.  Front pose is reasonable for humans, as if an mobile is created likely they will use front camera and properly show face, it is not a burden for the user. In situations where clearly presented face is not available, alternative system would be to use more images of humans, where face is not clearly visible. Given face detector is reasonably well, I would use this system as a secondary detection logic, first check if face is avaible, if so use standart face detector, then if not available use secondary system to see if he/she is human. Then go on with dog classifier system. For alternative face detection algorithm LBP Cascade classifier was tested , although human positive detection fell to 88% percent, it has better job as not detecting dogs as humans with %1 percent.
## (Optional) TODO: Report the performance of another
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
face_cascade_lbp = cv2.CascadeClassifier('haarcascades/lbpcascade_frontalface_improved.xml')
#alternate detector
def face_detector_lbp(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade_lbp.detectMultiScale(gray)
return len(faces) > 0
# load color (BGR) image
img = cv2.imread(human_files[110])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade_lbp.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
human_human_detected_count = sum(1 for is_human in human_files_short if face_detector_lbp(is_human))
dog_human_detected_count = sum(1 for is_human in dog_files_short if face_detector_lbp(is_human))
print("Detected {} humans in human files of total {} , ratio: {}".format(human_human_detected_count,len(human_files_short),human_human_detected_count/len(human_files_short) ) )
print("Detected {} humans in dog files of total {} , ratio: {}".format(dog_human_detected_count,len(dog_files_short),dog_human_detected_count/len(dog_files_short) ) )
In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.
from keras.applications.resnet50 import ResNet50
# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape
$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$where nb_samples
corresponds to the total number of images (or samples), and rows
, columns
, and channels
correspond to the number of rows, columns, and channels for each image, respectively.
The path_to_tensor
function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape
The paths_to_tensor
function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape
Here, nb_samples
is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples
as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!
from keras.preprocessing import image
from tqdm import tqdm
def path_to_tensor(img_path):
# loads RGB image as PIL.Image.Image type
img = image.load_img(img_path, target_size=(224, 224))
# convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
x = image.img_to_array(img)
# convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
return np.expand_dims(x, axis=0)
def paths_to_tensor(img_paths):
list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
return np.vstack(list_of_tensors)
Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input
. If you're curious, you can check the code for preprocess_input
here.
Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict
method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels
function below.
By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.
from keras.applications.resnet50 import preprocess_input, decode_predictions
def ResNet50_predict_labels(img_path):
# returns prediction vector for image located at img_path
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(ResNet50_model.predict(img))
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua'
to 'Mexican hairless'
. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels
function above returns a value between 151 and 268 (inclusive).
We use these ideas to complete the dog_detector
function below, which returns True
if a dog is detected in an image (and False
if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
Question 3: Use the code cell below to test the performance of your dog_detector
function.
human_files_short
have a detected dog? dog_files_short
have a detected dog?Answer:
human_files_short
%1 percent of humans were detected as dogdog_files_short
%100 percent of dogs were detected as dog### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
humans_detected_as_dog_count = sum(1 for is_human in human_files_short if dog_detector(is_human))
dogs_detected_as_dog_count = sum(1 for is_human in dog_files_short if dog_detector(is_human))
print("Detected {} dogs in human files of total {} , ratio: {}".format(humans_detected_as_dog_count,len(human_files_short),humans_detected_as_dog_count/len(human_files_short) ) )
print("Detected {} dogs in dog files of total {} , ratio: {}".format(dogs_detected_as_dog_count,len(dog_files_short),dogs_detected_as_dog_count/len(dog_files_short) ) )
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
We rescale the images by dividing every pixel in every image by 255.
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files)≈
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
model.summary()
We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.
Answer: Test accuracy of 11.1244% was calculated with the base architecture and Swish activation function via https://www.kaggle.com/shahariar/keras-swish-activation-acc-0-996-top-7 . In order to reduce training time, model was modified with reduced filter size with strides. Higher accuracy may be available if stride window of 1 is used and filter sizes for convolutional filters increased.
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]
print("Number of dog breeds: {}".format(len(dog_names)))
# For adding new activation function
from keras import backend as K
from keras.utils.generic_utils import get_custom_objects
class swish_a(Activation):
def __init__(self, activation, **kwargs):
super(swish_a, self).__init__(activation, **kwargs)
self.__name__ = 'swish'
def swish(x):
return (K.sigmoid(x) * x)
get_custom_objects().update({'swish': swish_a(swish)})
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, Activation
from keras.models import Sequential
model = Sequential()
### TODO: Define your architecture.
#kernel size = length of 1D convolution window
#stride = stride length of the convolution
#padding = 'valid' --> no padding
""" architecture from https://www.kaggle.com/shahariar/keras-swish-activation-acc-0-996-top-7 """
model.add(Conv2D(filters = 16, kernel_size = (5,5),strides = (2,2),padding = 'Same',
activation ='swish', input_shape = (224, 224, 3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),strides = (2,2),padding = 'Same',
activation ='swish'))
model.add(MaxPooling2D(pool_size=(3,3)))
model.add(Dropout(0.25))
#model.add(Conv2D(filters = 32, kernel_size = (3,3),padding = 'Same',
# activation ='swish'))
model.add(Conv2D(filters = 32, kernel_size = (3,3),padding = 'Same',
activation ='swish'))
model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "swish")) ## too many parameters
#model.add(Dense(128, activation = "swish"))
model.add(Dropout(0.25))
model.add(Dense(len(dog_names), activation = "sigmoid"))
model.summary()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
from keras.callbacks import ModelCheckpoint
### TODO: specify the number of epochs that you would like to use to train the model.
#number of epochs to train for
epochs = 20
### Do NOT modify the code below this line.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
verbose=1, save_best_only=True)
model.fit(train_tensors, train_targets,
validation_data=(valid_tensors, valid_targets),
epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary()
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5',
verbose=1, save_best_only=True)
VGG16_model.fit(train_VGG16, train_targets,
validation_data=(valid_VGG16, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')
Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
from extract_bottleneck_features import *
def VGG16_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = VGG16_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)]
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:
The files are encoded as such:
Dog{network}Data.npz
where {network}
, in the above filename, can be one of VGG19
, Resnet50
, InceptionV3
, or Xception
. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/
folder in the repository.
In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:
bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
<your model's name>.summary()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: Resnet 50 model was chosen. Resnet50 uses residual learning with 50 layers, where residual functions are used in n+x'th layer using input from n'th layer. Using this gives better accuracy. More layers can be used, impacting training speed. This architecture has more layers than VGG but has lower complexity. Resnet architecture was especially designed for face detection so it is proper to use this architecture.
### TODO: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))
Resnet50_model.summary()
### TODO: Compile the model.
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5',
verbose=1, save_best_only=True)
Resnet50_model.fit(train_Resnet50, train_targets,
validation_data=(valid_Resnet50, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
### TODO: Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]
# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher
, Afghan_hound
, etc) that is predicted by your model.
Similar to the analogous function in Step 5, your function should have three steps:
dog_names
array defined in Step 0 of this notebook to return the corresponding breed.The functions to extract the bottleneck features can be found in extract_bottleneck_features.py
, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function
extract_{network}
where {network}
, in the above filename, should be one of VGG19
, Resnet50
, InceptionV3
, or Xception
.
from ipywidgets import FloatProgress
from IPython.display import display
def predict_dog_breed(path, num_best_pred=2, debug = False):
"""
Takes a path to an image , and number of predictions(optional) as input
and returns the dog breed array with probabilities that is predicted by the model.
By default returns top two breeds.
"""
f = FloatProgress(min=0, max=100)
display(f)
f.value += 2
#load image
if debug: print('Load image.')
image_for_keras = path_to_tensor(path)
f.value += 2
#get bottleneck for Resnet50
if debug: print('Extract Resnet bottleneck feats.')
bottleneck_feats = extract_Resnet50(image_for_keras)
f.value += 50
#use top model for prediction
if debug: print('Feeding top model...')
prediction = Resnet50_model.predict(bottleneck_feats)[0]
f.value += 40
# sort predicted breeds by highest probability, get top num_best_pred predictions
# output is array of tuples with dog name and prediction
if debug: print('Predicting dog breed...')
breed_dict = [( dog_names[idx], prediction[idx]) for idx in (-prediction).argsort()[:num_best_pred]]
f.value += 50
return breed_dict
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector
and dog_detector
functions developed above. You are required to use your CNN from Step 5 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
%matplotlib inline
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
def predict_dog_in_image(image_path, num_breeds=2):
"""
Predict dog breed in image path
If probability is lower than 60 percent prediction and second guess will be printed
"""
print("Checking what dog you are ...")
breeds = predict_dog_breed(image_path, num_breeds)
img = mpimg.imread(image_path)
#check if there are dogs in image
if dog_detector(image_path):
#this very highly a dog image
#Show that this is a dog image show breed and exit
fig = plt.figure()
fig.suptitle("Hello DOG!", fontsize=14)
imgplot = plt.imshow(img)
plt.axis('off')
top_prediction_confidence= breeds[0][1]
plt.title("You seem like a {}".format(breeds[0][0]))
if top_prediction_confidence< 0.6:
print("You seem to be a mix of:")
print("{} with {} probability".format(breeds[0][0],breeds[0][1]))
print("and {} with {} probability".format(breeds[1][0], breeds[1][1]))
return
#image was not a dog, check if he/she is human
if face_detector(image_path):
#this is likely a human image
#show what dog breed human looks like and return
fig = plt.figure()
fig.suptitle("Hello HUMAN!", fontsize=14)
imgplot = plt.imshow(img)
plt.axis('off')
top_prediction_confidence= breeds[0][1]
plt.title("You seem like a {}".format(breeds[0][0]))
if top_prediction_confidence< 0.6:
print("You seem to be a mix of:")
print("{} with {} probability".format(breeds[0][0],breeds[0][1]))
print("and {} with {} probability".format(breeds[1][0], breeds[1][1]))
return
#image was not detected either as a dog or human
#show some error
fig = plt.figure()
fig.suptitle("Hello Whatever You are!", fontsize=14)
imgplot = plt.imshow(img)
plt.axis('off')
print("Unable to detect a dog or a human in the image.\n May be this is a cat!")
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: Output is generally good if front face of human or dog is presented. Likely due to some dog breeds being mixed, algorithm can not predict with higher intensity.For example German Shephard dog below was predicted with %52.8 accuracy, for a bigger than 50% classifier this can be good but for more precision images (where multi classes are used) this may not give correct result. Nearest prediction of Belgian Malionis does indeed look alike shephard but has slowly different body.
For a pure face classifier algorithm is generally good, but if we want to more correctly classify dog breeds additional features should be used, and those can be done with image augmentation.
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
predict_dog_in_image('images/dog1.jpg')
predict_dog_in_image('images/dog2.jpg')
predict_dog_in_image('images/mark.jpg')
predict_dog_in_image('images/gorkem.jpg')
predict_dog_in_image('images/dog3.jpg')
predict_dog_in_image('images/dog4.jpg')
predict_dog_in_image('images/woman.jpg')
predict_dog_in_image('images/cat.jpg')


Dockers secure young gun Luke Ryan with new long-term deal
by Ben WaterworthFremantle has locked away arguably its biggest name that was out of contract at the end of next year, with Luke Ryan recommitting to the club.
The Dockers confirmed on Tuesday that Ryan had signed a three-year contract extension on top of the season he already had left to run, therefore tying him to the club until at least the end of 2023.
Ryan, 23, has become one of the key cogs in Fremantle’s backline since it drafted him with Pick 66 in 2016 as a mature-age prospect.
Stream over 50 sports live & anytime on your TV or favourite device with KAYO SPORTS. The biggest Aussie sports and the best from overseas. Just $25/month. No lock-in contract. Get your 14 day free trial >
Rated elite for intercept possessions and intercept marks according to Champion Data, Ryan said he was keen to repay the faith Fremantle had shown in him.
“I’ve got my family back home but when I spoke to them, we came to the conclusion that Fremantle gave me my chance – if it wasn’t for Fremantle I probably wouldn’t have been playing AFL.
“(Before) I was called out with pick 66, I felt it was my last chance and, luckily enough, they called me. I owe it to Fremantle and what they’ve done for me, so I wanted to sign on.”
Ryan, who was ranked second in the AFL for average intercepts in 2019, has played 49 games in three seasons.
Fremantle list manager Mark Micallef said Ryan had established himself the club’s defensive set-up and had high hopes for him.
“With Luke’s intercept ability and ability to use the ball by foot, he adds to the defensive pillars we have in our defence,” Micallef said.
“We see Luke as being a really strong and hopefully elite player of the competition. He has the football characteristics that are vital for our success and we hope he can lock in that role as a strong leader of our defence.”


pyLDAvis In org-mode With JQuery
Table of Contents
Introduction
In my last post I loaded the pyLDAvis widget by dumping the HTML/Javascript right into the org-mode document. The problem with doing this is that the document has a lot of lines of text in it, which slows down emacs a noticeable amount, making it hard to display one widget, and pretty much impractical to show more than one. So, since Nikola (or maybe bootstrap or one of the other plugins I'm using) is loading JQuery anyway, I'm going to use javascript to add the HTML after it loads from a file.
Imports
Python
datetime
is just to show how long things take. In this case the data-set is fairly small so it doesn't take very long, but in other cases it might take a very long time to build the LDA model so I like to time it so I know the next time about how long I should wait.
from datetime import datetime
from pathlib import Path
From PyPi
from sklearn.datasets import fetch_20newsgroups
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
import pyLDAvis
import pyLDAvis.sklearn
The Data
I'm going to use the Twenty Newsgroups data-set, not because of anything significant, but because sklearn has a downloader for it so I figured it'd be easiest.
path = Path("~/datasets/newsgroups/").expanduser()
newsgroups = fetch_20newsgroups(data_home=path, subset="train")
print(path)
/home/brunhilde/datasets/newsgroups
The newsgroups.data
is a list, so it doesn't have a shape attribute like it would it it were a numpy array.
print("{:,}".format(len(newsgroups.data)))
print("{:.2f}".format(len(newsgroups.data)/18000))
11,314 0.63
The documentation for the fetch_20newsgroups
function says that the full dataset has 18,000 entries, so we have about 63% of the full set.
The Vectorizer
I'm going to use sklearn's CountVectorizer to convert the newsgroups documents to arrays of token counts. This is about the visualization, not making an accurate model so I'm going to use the built-in tokenizer. I'm not sure what the fit
method is for, but the fit_transform method returns the document-term matrix that we need (each row represents a document, the columns are the tokens, and the cells hold the counts for each token in the document).
started = datetime.now()
vectorizer = CountVectorizer(stop_words="english")
document_term_matrix = vectorizer.fit_transform(newsgroups.data)
print("Elapsed: {}".format(datetime.now() - started))
Elapsed: 0:00:03.033235
The LDA
Now we'll build the Latent Dirichlet Allocation Model.
start = datetime.now()
topics = len(newsgroups.target_names)
lda = LatentDirichletAllocation(topics)
lda.fit(document_term_matrix)
print("Elapsed: {}".format(datetime.now() - start))
Elapsed: 0:02:37.479097
PyLDAvis
Okay so here's where we try and get pyLDAvis into this thing.
Prepare the Data for the Visualization
The Prepared Data
The first step in using pyLDAvis is to create a PreparedData
named-tuple using the prepare function.
start = datetime.now()
prepared_data = pyLDAvis.sklearn.prepare(lda, document_term_matrix, vectorizer)
print("Elapsed: {}".format(datetime.now() - start))
Elapsed: 0:00:34.293668
Build the HTML
Now we can create an HTML fragment using the prepared_data function. The output is a string of HTML script, style, and div tags. It adds the entire data-set as a javascript object so the more data you have, the longer the string will be.
div_id = "pyldavis-in-org-mode"
html = pyLDAvis.prepared_data_to_html(prepared_data,
template_type="simple",
visid=div_id)
Export the HTML
Now I'm going to save the html to a file so we can load it later.
slug = "pyldavis-in-org-mode-with-jquery"
posts = Path("../files/posts/")
folder = posts.joinpath(slug)
filename = "pyldavis_fragment.html"
if not folder.is_dir():
folder.mkdir()
output = folder.joinpath(filename)
output.write_text(html)
assert output.is_file()
So here's where we create the HTML that will be embedded in this post. The JQuery load function puts the content of our saved file into the div. I added the css call because I have my site's font-size set to extra-large, since the Goudy Bookstyle looks too small to me otherwise (I think nice fonts look better when they're big), which causes the buttons in the pyLDAvis widget to overflow out of the header. Under normal circumstances you wouldn't need to do this, but if you do want to do any one-off styling, here's an example of how to do it. Otherwise maybe an update to the style-sheet would be better.
The right-hand box is still messed up, but it's good enough for this example.
print('''#+BEGIN_EXPORT html

#+END_EXPORT'''.format(div_id, filename))


About Han
Do greatest at in learning steepest. Breakfast extremity suffering one who all otherwise suspected. He at no nothing forbade up moments. Wholly uneasy at missed be of pretty whence. John way sir high than law who week. Surrounded prosperous introduced it if is up dispatched. Improved so strictly produced answered elegance is.
Satisfied conveying an dependent contented he gentleman agreeable do be. Warrant private blushes removed an in equally totally if. Delivered dejection necessary objection do mr prevailed. Mr feeling do chiefly cordial in do. Water timed folly right aware if oh truth. Imprudence attachment him his for sympathize. Large above be to means. Dashwood do provided stronger is. But discretion frequently sir the she instrument unaffected admiration everything.
Abilities forfeited situation extremely my to he resembled. Old had conviction discretion understood put principles you. Match means keeps round one her quick. She forming two comfort invited. Yet she income effect edward. Entire desire way design few. Mrs sentiments led solicitude estimating friendship fat. Meant those event is weeks state it to or. Boy but has folly charm there its. Its fact ten spot drew.
So feel been kept be at gate. Be september it extensive oh concluded of certainty. In read most gate at body held it ever no. Talking justice welcome message inquiry in started of am me. Led own hearted highest visited lasting sir through compass his. Guest tiled he quick by so these trees am. It announcing alteration at surrounded comparison.


This document set describes the public APIs and SPIs offered by the Registry module.
Contents
API (including overview and examples)
SPI
MergedContexts
Additional documentation:
Design Choices
Change History
Architecture Summary
Credits:
The Registry API was strongly inpired by Preferences API and JNDI API. Several people from nbdev mailing list (especially Jesse Glick, Radek Matous, Petr Nejedly, Vitezslav Stejskal, Jaroslav Tulach) provided valuable feedback which was incorporated.
<WARNING>
Current
implementation of the Registry uses for object persistence DataSystem
layer and its InstanceDataObject. This will be changed before final
release and this change can significantly change the behaviour how
object are treated. For example current InstanceDataObject
automatically saves object when it was modified. You just retrieve the
object from Registry API, modify the object through its API and the
object will be automatically persist without the need to bind the
changed object back to Registry. This is one of the things which can
change when dependency on DataSystem is eliminated. If you are
switching to Registry API please keep this in mind, ask questions, mark
the source code to be able to return to is later etc. See Settings Redesign page for the most actual info.
</WARNING>


1 Writing recursive functions
In this recipe, we will be looking at writing recursive functions, and tail recursions which will allow efficient, infinite recursion.
We will take famous fibonacci number to implement our solution. We will then take this very simple solution and then convert it to a tail recursive efficient solution.
1.1 Fibonacci Number
We know that, the first two fibonacci numbers are 0, and 1, and remaining numbers are calculated by a simple formula,
\(fib(n) = fib(n-1) + fib(n-2)\)
1.2 Recursive solution
Now we can implement the solution. First we will start with declaration.
fib :: Int -> Int
Given an integer argument, n, we will return n'th fibonacci number.
1.2.1 Base cases
The base cases are straight forward, we disallow negative arguments. And precalculate 0'th and 1'st fibonacci numbers.
fib n | n < 0 = error "Negative index" fib 0 = 0 fib 1 = 1
1.2.2 Remaining cases
All that remains is to calculate the remaining cases,
fib n = fib (n-1) + fib (n-2)
We have recursively called the same function.
1.2.3 Is recursive solution efficient
We can run the soltion to check the efficiency. In GHCi, we load the function, and set the timing/memory stats to be printed after each execution.
λ> :set +s
And now we can run the function 'fib' with increasing values.
λ> fib 10 55 (0.00 secs, 0 bytes) λ> fib 20 6765 (0.05 secs, 15,287,704 bytes) λ> fib 30 832040 (3.69 secs, 1,262,480,024 bytes)
You can easily see that though the implementation is simple, and even though the change in the input argument linear, the timing has shot up exponentially.
 And most importantly, the above implementation is not tail recursive. i.e. during the recursion, the recursive expression is not the function call itself. In the above implementation, "fib (n-1) + fib (n-2)" is the expression where recursion occurs. And since the expression actually is ( (+ ) (fib (n-1)) (fib (n-2))), one can see that the result expression contains an operation (+) which is required to be evaluated after calling the two recursive calls. This requires compiler to build up stack.
If on the other hand, if we can make the last expression, the function call itself, compiler can actually optimize the recursion in such a way that only function call is kept in the stack. This is called tail recursion.
1.2.4 Implementing tail recursive function by worker pattern
Since the very simple recursive definition is not efficient, we will convert the definition to a tail recursive. We use worker pattern here. In this pattern, we create a worker function and pass an additional argument where we keep the result. Whenever we hit the base case, we return the result.
In case of fibonacci number, the number depends upon two previous number. Let's use previous numbers as argument to our worker function.
fibworker :: Int -> Int -> Int -> Int fibworker n p1 p2 = _
Where p1 and p2 are previous fibonacci numbers respectively, and p1 > p2.
We then calculate, next number by adding two previous results, n1 and n2. Since this is a new number, we make following recursive call.
fibworker n p1 p2 = fib (n-1) (p1+p2) p1
Note that we have replaced previous fibonacci numbers p1 and p2 by (p1+p2) and p1 in the recursive calls. Also notice that we have reduced n to n-1 to indicate that we have done with a step in the calculation of fibonacci number.
The recursive call will soon hit '2' in the first argument. When that happens, we will be ready to spit out the result, by just adding two previous values.
Why '2', you might ask. Do remember in the worker we use two previous values. It means that we have to stop recursion at '2' when we already have two values.
fibworker 2 p1 p2 = p1 + p2
We can trivially complete the remaining cases, 0, and 1 by directly returning the result
fibworker 0 _ _ = 0 fibworker 1 _ _ = 1
We now can wrap worker in another function, called 'fib1' so that we can provide initial values to the worker function. The initial values are second and first fibonacci numbers, i.e. 1 and 0 respectively.
fib1 n | n < 0 = error "Negative index" fib1 n = fibworker n 1 0
Also notice that the fibworker is an internal function, and need not be used elsewhere, and hence we can move the whole definition of fibworker as a where construct,
fib1 n | n < 0 = error "Negative index" fib1 n = fibworker n 1 0 where fibworker :: Int -> Int -> Int -> Int fibworker 0 _ _ = 0 fibworker 1 _ _ = 1 fibworker 2 p1 p2 = p1 + p2 fibworker n p1 p2 = fibworker (n-1) (p1+p2) p1
1.2.5 Fibonacci Evaluator
The source for the fibonacci evaluator is given here.
module Fibonacci where -- Naive recursive fibonacci implementation. fib :: Int -> Int fib n | n < 0 = error "Negative index" fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) -- Efficient fibonacci implementation with worker pattern fib1 n | n < 0 = error "Negative index" fib1 n = fibworker n 1 0 where fibworker :: Int -> Int -> Int -> Int fibworker 0 _ _ = 0 fibworker 1 _ _ = 1 fibworker 2 p1 p2 = p1 + p2 fibworker n p1 p2 = fibworker (n-1) (p1+p2) p1


What is Apache OpenNLP?
Major Changes in this Release
How to Get Involved
How to Report Issues
List of JIRA Issues Fixed in this Release
The Apache OpenNLP library is a machine learning based toolkit for the processing of natural language text. It supports the most common NLP tasks, such as tokenization, sentence segmentation, part-of-speech tagging, named entity extraction, chunking, parsing, and coreference resolution. These tasks are usually required to build more advanced text processing services. OpenNLP also included maximum entropy and perceptron based machine learning.
The goal of the Apache OpenNLP project will be to create a mature toolkit for the above mentioned tasks. An additional goal is to provide a large number of pre-built models for a variety of languages, as well as the annotated text resources that those models are derived from.
Please see the README for this information.
The Apache OpenNLP project really needs and appreciates any contributions, including documentation help, source code and feedback. If you are interested in contributing, please visit http://opennlp.apache.org/
The Apache OpenNLP project uses JIRA for issue tracking. Please report any issues you find at http://issues.apache.org/jira/browse/opennlp
Click issuesFixed/jira-report.html for the list of issues fixed in this release.


Katie Price's bright pink Range Rover gets repossessed after bankruptcy rumours
Katie Price had her iconic pink Range Rover repossessed a month after getting a two-year driving ban.
The former glamour model’s car was seen at Saxton 4X4 in Chelmsford after it got purchased at a car auction last week.
Katie had been hit with a series of financial problems over the last year, which almost led to her declaring bankruptcy and entering into an Individual Voluntary Agreement.
The word ‘repo’ was marked on the car’s windscreen but there has not been any further information released on what is happening with Katie.
Her £75,000 Range Rover is possible the same one she was in when she was arrested for driving under the influence in 2018.
Katie’s luck with cars just seems to be getting worse and worse.
A witness told MailOnline: ‘It’s a very striking car but we didn’t know straight away that it belonged to Katie Price.
Advertisement Advertisement
‘But then one of the buyers told us that it was hers. We couldn’t believe how filthy it was.’
The star – who started her own YouTube channel – was spotted getting a couple lines on the Euromillions lottery last month after news broke of her apparent bankruptcy last month.
She entered into an ongoing Individual Voluntary Arrangement with debtors in 2018.
It reportedly allowed her to pay £12,000 a month over the course of four years.
But a bankruptcy petition was placed on the IVA, and at a hearing at the Insolvency and Companies Court on Monday 18 October, Judge Sally Barber ordered the 41-year-old to be served with a draft petition notice within seven days.
Metro.co.uk have contacted reps for comment.
Got a showbiz story?
If you've got a story, video or pictures get in touch with the Metro.co.uk Entertainment team by emailing us<EMAIL_ADDRESS>calling 020 3615 2145 or by visiting our Submit Stuff page - we'd love to hear from you.


This post is the first in the series of “From JavaScript to Ruby”, which is aimed at helping JavaScript developers transition their thinking from JavaScript to Ruby. This post will answer this fundamental question: how do I do “callbacks” in Ruby? The answer is: the “idiomatic” way (we’ll talk about what “idiomatic” means) to use so-called callbacks in Ruby is to use blocks. We’ll discuss blocks, and their similarities to JavaScript callbacks.
Defining “callback” through practical examples
A callback is a function that happens after we call another function, but the catch is, they’re coupled. However, being coupled in this way doesn’t mean we can’t reuse the callback function.
We often use anonymous functions in JavaScript as callbacks. Here’s an example using Array.prototype.forEach
:
We can actually sort of “scoop out” the function that we passed into Array.prototype.forEach
in order to make it reusable:
How do we do this in Ruby? And what does “idiomatic” mean?
You’ll hear a lot of Rubyists use the word “idiomatic”. Read:
The idiomatic way to pass arguments to a method in Ruby is such and such…
The idiomatic way to use a “callback” in Ruby is to such and such…
In normal-people speak, you’d say:
The common way to go about doing this is such and such…
Make sense? In other words, there are certain patterns and best practices (solutions) for common problems in Ruby: we call these solutions “idioms”. So, the idiomatic way to use callbacks in Ruby is not to use callbacks at all. Instead, we use blocks.
Here’s how we can do the same exact thing in Ruby, instead of JavaScript:
If you run the above, you’ll see Hello <name>
printed for each name, and at the end it’ll actually return the entire array for you to use.
Let’s compare the two. Essentially, this JavaScript…:
…is the same as this Ruby:
We can also write the above Ruby in another, shorter way:
So here’s a few things we’ve learned from the above.
1st thing we learned (string interpolation)
Both ways are correct, but the string interpolation notation is more idiomatic.
In JavaScript, we call it “string concatenation”:
2nd thing we learned (block syntax)
We also learned two styles, or syntaxes, for writing blocks:
Pro Tip
Before we continue, I want to point out a couple style points. Rubyists often use "soft tabs", or 2 spaces instead of just a 4-character tab, only because it different environments it remains readable (see this StackOVerflow question). Also, look at the spacing between the curly braces and pipes. I recommend something to you: Rubocop, which is sort of the de-facto command line tool that tells you if your code looks bad according to the community style guide on GitHub. It's good stuff.
3rd thing we learned (Enumerable#each == Array.prototype.forEach
)
Continuing, we learned that Ruby’s Enumerable#each
is equivalent to JavaScript’s Array.prototype.forEach
(more or less). I have found only one online blog post so far that has made Ruby’s #each
make sense to me. It is by Erik Trautman.
“Scooping out” the block like a reusable callback
There are two common ways to make a reusable “callback” in Ruby. They are the lambda
and the Proc
. There are very subtle differences between the two ways.
Lambda
By the way, that’s the new syntax for the single-line lambda as of Ruby 1.9 (I have Ruby 2.1 right now, if you’re curious).  Let’s make it look even weirder:
Proc (short for “procedure”)
Did you notice, by the way, that you can do multi-line variable assignment? Pretty cool; you can’t do that in JavaScript.
Differences
- Lambda:
- You don’t have to pass in all the arguments if you don’t want to. If your “callback” needs, say, 3 arguments, and you only pass in 2 when you use it, there will be no error. This is just like a JavaScript callback… but in JavaScript, the undefined arguments will be
undefined
, and in Ruby, the undefined arguments will benil
. - If you call
return <whatever>
, the lambda stops, but any method that the lambda is in does not stop. You can use the lambda’s returned value in the rest of the containing method.
- You don’t have to pass in all the arguments if you don’t want to. If your “callback” needs, say, 3 arguments, and you only pass in 2 when you use it, there will be no error. This is just like a JavaScript callback… but in JavaScript, the undefined arguments will be
- Proc:
- You must pass in all the arguments, or you’ll get an error.
- If you call
return <whatever>
, the Proc and any method that it is in will stop. The Proc will return its value to the containing method, and the containing method will also return that same value.
lambda
in JavaScript:
Proc
in JavaScript:
In Ruby, though, as a side note, we rarely use an explicit return
statement. You can just type a value.
This JavaScript…:
…is equivalent to this Ruby:
The ampersand (&
)
This confusing thing basically just makes sure the thing you’re passing into the method is a Proc, sort of. You can read about that in detail on a.blog.about.code.
The above error is basically saying, “why did you pass me an argument? I expected 0 arguments for #each
”. &sayHello
is not an argument! It is a Proc
, and Ruby does not count Proc
s as arguments!
It’s weird, huh? That’s because you can pass in a block at the end of pretty much any method in Ruby, and it won’t see it as an argument, in the typical sense.
Check it out:
We passed in a block at the end, but it didn’t run. But we didn’t get any error either. If we want the block to actually run, we can just say yield
:
#block_given?
is a native method that returns a boolean (true
or false
) that checks if a block was passed in to the method. We have to use it in the above example, because if we just say yield
instead of yield if block_given?
, then we’ll get an error that says no block given (yield)
.
Also, the question mark ?
is Ruby’s way of meaningfully letting the user know that the method is supposed to return a boolean. There’s nothing really special about it.
Now, going back to the original error (error: wrong number of arguments (1 for 0)
):
I’ll try my best to sort of construe a similar error in JavaScript:
If the above code were Ruby, you’d get an error something like wrong number of arguments (2 for 1)
. Once again, I want to emphasize this is because Ruby doesn’t see the Proc
as an argument.
Conclusion
- Use blocks as if they were callbacks.
- Use a
lambda
or aProc
. Remember the two subtle differences between them (number of arguments, and return values). - Put a
&
before the block that you pass into the method, if you pass it in to a native Ruby method that will run a block, likeEnumberable#each
.
Further reading
- Reactive.IO: Understanding Ruby Blocks, Procs, and Lambdas
- makandracards: Short Lambda Syntax in Ruby 1.9


Takamul Project Management Company (Takamul) is a specialized, integrated project management firm dedicated to promoting the project management practice in the Kingdom of Saudi Arabia.
In 2011, Salem H. Shaheen, and in cooperation with prominent Saudi businessman and project management professionals, founded Takamul to promote professional project management in Saudi Arabia and provide independent expertise, opinion and advice to public and private projects owners in Saudi Arabia and in GCC, starting with the King Abdullah City for Atomic and Renewable Energy (KA-CARE) project in Riyadh.
Takamul assists corporate, governmental, and private clients across various industries to complete their projects On-Time and Within Budget with Right Scope and Required Quality, thus maximizing the return on their investments. Originally established to promote the project management profession combining international experience with local knowledge that fully understands the culture of Saudi Arabia and the Gulf region countries and the characteristics of the construction industry herein.
Takamul provides start-to-end professional program and project management consulting services working closely with our valued clients. We offer full project management solutions tailor made to suit each client with innovative approach. Our consulting services include the entire project lifecycle, starting from project development, scoping, pre-feasibility and feasibility studies, detailed design, tendering and procurement, contract management, construction management as well as commissioning and hand-over.
Takamul recognizes that the quality of our services hinges on the people who deliver it. Takamul’s team are passionate, driven professionals with initiative and hands-on experience in project management. As well as specialist in project management skills, Takamul’s team have a range of experience gained from having worked in complementary fields such as development, engineering consultancy, construction, infrastructure, and asset ownership.
With Takamul’s top management commitment, our team pride themselves on their energy, initiative and passion, and strives to deliver the best outcome for our clients, the project and the end user's on every project Takamul works on.


This was a project to build a prototype of a free-flying telepresence drone for the ISS, very similar to the 'Free Flying Robot' that NASA announced later.
We built a prototype with a selection of low-power fans, designed for safe operation in a pressurized microgravity environment. It's a bit like a quadcopter with a video camera, but since it doesn't need to fight gravity and does need to not break anything, the fans are much smaller.
The brains were supplied by an Odroid U3, a single-board Linux computer with a good bit more CPU power than the Raspberry PI. Fans were controller by a microcontroller and custom motor driver PCB. The UI was a web interface which presented low-latency streaming video, and gamepad and keyboard control to a Firefox or Chrome browser with no additional plugins or client software. A relay server was placed between the bot and users to handle video load and provide a security override.
Control software and misc. other things available in our GitHub repo.
We also submitted a proposal to CASIS for an earlier smartphone-based version of this project.


Due to the scope and nature of the Roman de la Rose Digital Library
project, this site remains under construction. Despite our best
efforts, we cannot guarantee that all content is accurate or complete,
and we ask that you contact us as indicated below if you find an error.
Please note that not all manuscripts have transcriptions and/or a
codicological description as of today. Many of the transcriptions
included here have not been checked for accuracy. This
information will be added as it becomes available and you are
encouraged to check back as necessary.
Please be aware that new folio numbers have been attributed to manuscripts with known errors of foliation.
Thank you for your patience and support of this evolving scholarly resource.
In order to identify priorities for additional content acquisition or feature development, we will use Google Analytics to track usage patterns by visitors to this site. The data collected are not connected to user's personal information or identity. For further information, please visit the Sheridan Libraries privacy policy.


_Girlfight_ (R) *** (out of ****)
Karyn Kusama's _Girlfight_ quite literally hits theatres with the formidable force of enthusiastic reviews and strong Sundance audience buzz behind it. But as is the case with a number of film festival favorites, the film's impact in a traditional cineplex setting, while potent, doesn't quite bowl one over. However, one thing about the film plays explosively in any viewing context--the blazing performance by newcomer Michelle Rodriguez.
_Girlfight_ would be unthinkable without Rodriguez as Diana Guzman, a Brooklyn teen whose hot temper often gets her in trouble at school. Diana inadvertently finds an outlet for her aggression when running a simple errand for her father (Paul Calderon) at the gym where her younger brother (Ray Santiago) takes boxing lessons. Seeing this as a way to gain respect from others--but, most importantly, herself--Diana starts taking lessons from her brother's coach Hector (Jaime Tirelli) without her always-disapproving father's awareness.
Kusama's story of empowerment and self-actualization follows a familiar narrative trajectory. Diana's new confidence gives her the courage to confront long-simmering issues with her father. Diana meets and falls for talented fellow boxer Adrian (Santiago Douglas), which plants the seeds for an easily foreseeable climax.
The audience may know exactly where _Girlfight_ is going, yet the film is still compelling, due in no small part to the grit Kusama brings to the picture. The locations and the largely unfamiliar (only Calderon, a bit player in _Pulp_Fiction_, is recognizable) faces add immeasurably to the authenticity of the piece. It also helps that the actors have the chops to make the contrived convincing.
Kusama's most impressive accomplishment is the character of Diana and her believable transition from uncontrollable, disrespectful kid to disciplined young woman. Especially realistic is how fairly unspectacular of a boxer she becomes, underscoring that it's not so much the physical ability Diana gains but the mental adjustment. A standard Hollywood production would lose sight of that in favor of flash and completely change her into an invincible superwoman; Kusama remembers this is amateur boxing after all, and Diana becomes a capable, competent fighter whose full potential has yet to be realized.
The same can't exactly be said about the Rodriguez, who is simply astounding in this, her professional acting debut. Rodriguez doesn't ever downplay Diana's harsher side, but her natural magnetism instantly hooks the viewer, and as Diana subtly oftens and grows to care more about herself, so does the audience about her. It's an amazingly fluid, complex performance, and if _Girlfight_ is just the beginning for Rodriguez, there will be no stopping this luminous talent.
Michael Dequina<EMAIL_ADDRESS>|<EMAIL_ADDRESS>|<EMAIL_ADDRESS>Mr. Brown's Movie Site: http://www.mrbrownmovies.com CinemaReview Magazine: http://www.CinemaReview.com on ICQ: #25289934 | on AOL Instant Messenger: MrBrown23
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


Routes leaving Painted Desert:
North, plain, to Buffalo Plains [as75], 7 days
East, to Ocean [at76], The Outer Sea, 2 days
South, desert, to Painted Desert [au75], 8 days
West, desert, to Painted Desert [at74], 8 days
Seen here:
Stack of nazgul [gy1l], nazgul, number: 4
Dalrena [i6g], refugee


Boxes below get highlighted whenever current viewport matches their expression. Alias of current breakpoint is visible in the top right corner.


Full Stack Web Dev ▪ Flutter Dev ▪ Graphics Designer
My name is Hrushikesh. I’m a junior from 🇮🇳 I'm a full-stack js developer 💻, flutter developer 📱, mentor 👨🏫 and, a learner 📕. I'm deeply passionate about software development. I believe in the power of community and love community-based learning.
GIET University, Gunupur
2018 - 2022
January 2021 - Present
In-house Internship Program with Industry Collaboration - by TCET, Mumbai
Objective
January 2021 - February 2021
November 2020 - December 2020
September 2020 - November 2020
" Always try to grab the opportunities! "
August 2020 - November 2020
July 2020
June 2020
January 2021 - Present
September 2020 - Present
GirlScript Gunupur Chapter is part of the official GirlScript Foundation and has on the route to imparting the best relevant education and glow up the light of creativity among all.
November 2019 - Present
Odisha Oracle Users Group is a technical organization supporting students on their skill enhancement. The vision of the organization is to prepare a student to be an adaptive, skillful and, ready-to-work person.
January 2019 - Present
November 2020
November 2020
September 2020
January 2021
July 2020
May 2019


Locations Visited
Location visited:
Nearby landmarks:
Time of year visited:
Enter Place
Locations:
Location name:
Nearby landmarks:
Time visited:


| This inspection reports on any uses of the eval ,setTimeout, setInterval functions, or allocation of a Function object in JavaScript. These functions are used to execute arbitrary strings of JavaScript text, often dynamically generated. This can be very confusing, and may be a security risk. |
| Powered by InspectionJS |


Residence in Huajiadi / Wonder Architecs
- Curated by 韩爽 - HAN Shuang
- about 4 hours
Interior Design · Chaoyang Qu, China
- version="1.0" encoding="UTF-8"? Interiors designers: Wonder Architecs
- AreaArea of this architecture projectArea: 78.0 m2
- version="1.0" encoding="UTF-8"?YearCompletion year of this architecture project Year: 2017
- version="1.0" encoding="UTF-8"?PhotographsPhotographs: Haiting Sun
- version="1.0" encoding="UTF-8"?ManufacturersBrands with products used in this architecture project Manufacturers: CR9, 宜家, 有所
- Designer in Charge Chong Wang
- Construction Junze Liu, Fuze Liu
More Specs Less Specs
Text description provided by the architects. The Huajiadi(means flower house place) is a very poetic name, but before 1990s, it was just a farmland for planting pepper. Now, you can't find any clue that this once was a pastoral, and it has already become part of this gigantic and chaotic city. The Huajiadi District built in 90s, lived the people of various kinds. They come and go, and the houses boom and bust while people keep weaving their own life.
1. The Opportunity of the Axis
An amateur naturalist wants to rebuild his life in this crowded old building. But the early design of this old-fashioned apartment is obviously not regular.
The airport expressway has a diagonal line connected to the second ring road in southeast area. The structure of the 45 degree corner in the area of Huajiadi hence has been formed, and it got complains from taxi drivers as they are accustomed to driving in the vertical and horizontal city. At the end of the last century, the construction of this street tower, naturally absorbed the slant line, so the triangle boundary line become a significant feature in the cross section of this small apartment.
From interior pictures posted on the housing website, toilet and kitchen appeared dead corner, the living room is separated into two cramped space, the bigger one with functional defects, cannot fit into proper size furniture. However, unexpectedly, at the same time this apartment layout creates a "multi perspective" groovy visual, similar to garden with diverging corridors.
2. The Inspiration of "Observation on the Road"
It is said that the Central Academy of Fine Art is a disastrous area for "road observation", and the area not far from the Academy also provides cannonball for "modernology". Similar problems exist within other old communities in Beijing. The saturated parking spaces force the original possible public space into a less than 50 square meters entrance. However, interesting public life are carried on each day. The wooden board that is close to the bawn is folded, and inside of it is full of mirrors, razors and turn into a barber place into a second. Beside the low tables and chairs, the cold winter still doesn't cover the enthusiasm of the old men playing chess. The repair booth retracted the iron facade, and all kinds of newspapers and beverages are lined up.
However, no matter how messy the day's chairs are, all the furniture at the end of the night is placed back to their spots, and all of them are stored without exception,change of furniture at the entrance). This cramped space actually contains public life of dozens people, this set of 70 square meters of furniture interior provides a very important designreference, a wooden table facilitates sleep, storage, work, leisure, and projection a serious of functions. Bedroom hides panel of reading table, with flexible single furniture and carpet collocation, easily change different life scenarios.
3. Room Building within a House
Painting ‘Saint Jerome in his study’ from National Gallery in London depicted a fun space containing a monocolor large furniture (including bookshelf, desk and seat) in vaulted interior. Floating above the light colored floor, dome structure inside of furniture and the vault arched window are echoed with each other. The left arch drawing the outline of the window, stretched views further beyond. In another Chinese classical illustrations ‘Greet the Parents’, the room of the architecture and the altar in the interior are integrated in balance, showing two different scales juxtaposedin a similar form.
The two drawings revealed some information: furniture and interior space are similar in harmony; two: interior and furniture have similar scaling relations, in other words, the furniture itself narrow the room. In this way, it will enlarge the sense of the interior space, expand the visual depth, and produce the feeling of overlapping perspective. This "Room Building" approach is used in many places, such as table with view frame at entrance door, it will open the view, while window space designed in living room and bedrooms and kitchen created different forms of "window Pavilion". The local wood furniture in the whole white space created "framed scenery". The variation of material expression produced more spacial experience.
4. A growth ring for an ordinary apartment
The interior design often will erase the past history completely, but there is still hope to leave some ‘memory’ here. A material with maximized usage on one hand,reduces the cost of the transformation of hydropower, and on the other hand, carried some experiments on furniture’s "medieval collage". The leftover of the glass table used as supporting structure of wood desktop, showing slender legs.
During the construction we found folding door is over heavy, so it is decided to cut out 1m diameter semi-circle, combined with IKEA column legs, a push and pull table is made for ‘eating’, ‘work’, ‘dressing’ three functions.The black cabinets were cut in half, combined with IKEA legs formed kitchen cabinets.


Consensus is the best way to stay in the know about what’s going on in your neighborhood—whether it’s finding a last-minute babysitter, learning about an upcoming block party, or hearing about a rash of car break-ins. There are so many ways our neighbors can help us. We just need an easier way to connect with them.


{% extends "base.html" %} {% block title %}Welcome to the Online Skeptical Toolbox!{% endblock %} {% block content %}
This is a simple proof of concept web app that attempts to implement the ideas in Proposal: An online skeptical toolbox. The idea is simple: Enter the URL of a news article or blog post whose trustworthiness you'd like to evaluate, hit Analyze, and see a host of results that you can use to help form your opinion on the veracity of the writing.
To try it on some timely examples:
The GitHub project is at github.com/matthewcornell/skeptical-toolbox
{% endblock %} {% block scripts %} {% endblock %}


{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %}
I will put the discription of my project here.
Visit the about page to learn more!


teaching
classes, guest lectures and more
classes
- (Upcoming) USC CSCI 499: Language Models in NLP
- Fall 2023
- USC CSCI 699: Data-Centric NLP
- Fall 2022
guest lectures
- Introduction to Engineering for USC Viterbi K-12 Discover Engineering
- Host Instructor: Darin Gray
- Summer 2023 / Slides
- Research Overview for USC CS 697: Seminar in Computer Science Research
- Host Instructor: Maja Matarić
- Spring 2023
- What’s in a dataset? for USC CSCI 697: Seminar in Computer Science Research
- Host Instructor: Cyrus Shahabi
- Spring 2022
- Data Centric NLP for UMinnesota CSCI 8980: Intro to NLP Research
- Host Instructor: Dongyeop Kang
- Spring 2022
- Annotating Ambiguous NLI for MilaNLP: Coding Aperitivo
- Host Instructor: Dirk Hovy
- Spring 2022
- Transfer Learning for UW DATA 598: Statistical Deep Learning
- Host Instructor: Zaid Harachoui
- Spring 2021 / Slides
- Biases and Interpretability for UT-Austin CS395T: Topics in Natural Language Processing
- Host Instructor: Eunsol Choi
- Fall 2020 / Slides
- Phrase-Structure Parsing for UW CSE 447/547: Natural Language Processing
- Co-taught with Jungo Kasai. Host Instructor: Noah Smith
- Winter 2019 / Slides
- Minimum Bayes Risk decoding in UW CSE 599 D1: Advanced Topics in Natural Language Processing
- Host Instructor: Waleed Ammar
- Spring 2018
- Dependency Parsing for UW CSEP 517: Natural Language Processing
- Host Instructor: Noah Smith
- Spring 2018
- Unsupervised Learning for UW CSE 446: Machine Learning
- Host Instructor: Noah Smith
- Fall 2017 / Slides
- Dependency Parsing with the Chu-Liu-Edmonds algorithm for CMU 11-711: Algorithms for NLP.
- Co-taught with Sam Thomson. Host Instructors: Chris Dyer, Alon Lavie and Bob Frederking
- Fall 2014 / Slides
tutorials
- OAMLS: Online Asian Machine Learning School at ACML 2022.
- Slides
- Dec 9, 2022
- Transfer Learning in Natural Language Processing at NAACL 2019.
- Multilingual FrameNet at COLING 2018.
teaching assistantship
- Head TA for CMU 11-411: Undergrad NLP.
- Primary Instructors: Chris Dyer, Alon W Black, and Shomir Wilson
- Spring 2015


Select a tool
Line
Rectangle
Circle
Free Hand
Curve
Flood fill
Eraser
Image Upload
Text
Clear Canvas
Save Image
Chain
Fill
clockwise
Text Size (10 to 50):
Select a tool to start drawing


The fact that Error.Last is not eNoError does not necessarily mean that the previous predefined function failed or failed completely. Error.Last also returns a number of warning codes. For example, if a user specifies a number larger than maxcolor for the color parameter of the Draw.Line procedure, the line is still drawn, only in color maxcolor. However, Error.Last will return a code that warns the user of the fact.
var f : int
open : f, "testdata/information.txt", get
if f <= 0 then
put "File opened"
else
put "Could not open file."
put "Error Number: ", Error.Last
put "Error Message: ", Error.LastMsg
put "Error Constant: ", Error.LastStr
end if
This means that you can only call the function by calling Error.Last, not by calling Last.


Sharing Debugger
Sharing Debugger
History
Debug
Warnings That Should Be Fixed
How we scraped the URL
Fetched URL
Canonical URL
Link Preview
Based on the raw tags, we constructed the following Open Graph properties.


Traffic clear on I-20 westbound near Well Road
by KNOEWEST MONROE, La. (KNOE) - UPDATE: Traffic now appears to be moving smoothly.
--------
The latest update (7:58 p.m.) from the DOTD says, "There is heavy congestion I-20 West from Thomas Road (mile marker 114) to LA 546 (mile marker 109) due to a previous incident involving a tractor trailer. Expect delays."
On state traffic cams, the area near Thomas Road appears to be flowing smoothly.
-------
Traffic appears to be backed up on I-20 westbound near Well Road.
State traffic cameras show traffic moving at a very slow pace or not at all.
Waze users report that an accident is to blame. Police lights can be seen on state traffic cameras.
Traffic cameras at Thomas and at Stella appear to show traffic moving at a relatively slow pace.
The roads are also wet due to recent weather conditions.
Google Maps shows heavy traffic along I-20 westbound in West Monroe. Cypress Street also appears to have heavy traffic.


Change dir to NexT directory. There must be layout
, source
, languages
and other directories:
$ cd themes/next
$ ls
bower.json _config.yml docs gulpfile.coffee languages layout LICENSE.md package.json README.md scripts source test
Install module to source/lib
directory:
$ git clone https://github.com/theme-next/theme-next-canvas-ribbon source/lib/canvas-ribbon
Enable module in NexT _config.yml
file:
canvas_ribbon:
enable: true
$ cd themes/next/source/lib/canvas-ribbon
$ git pull


Pakistan successfully test-fires nuclear-capable missile
Shaheen-I has a range of 650 km.
by PRESS TRUST OF INDIAPakistan on Monday successfully test-fired a nuclear-capable surface-to-surface ballistic missile which can strike targets up to 650 km, bringing many Indian cities under its range.
According to a press release issued by the media wing of the Pakistani military, the launch of the Shaheen-I missile was held as part of a training exercise “aimed at testing the operational readiness of Army Strategic Forces Command”. The Shaheen-1 missile is capable of delivering all types of warheads up to range of 650 km, the Inter-Services Public Relations tweeted.
“Troops displayed a high standard of proficiency in handling and operating the weapon system, ensuring Pakistan’s credible minimum deterrence,” it said.


Mad World
The Mad World lyrics
The Alex Webcomic
The Mad World Webcomic
Mad World - Cover
< Next
Choose a page
Mad World Cover Quote
Character Page
Opening Comic
Opening Comic (Black and White)
Chapter Uno: All Around Me
Page 1
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
Page 8
Page 9
Page 10
Page 11
Page 12
Page 13
Previous >
Comment Form
is loading comments...
-->
© 2014 Kevin Soria. All Rights Reserves. Kevin, Kevin Soria, and all photos of Kevin Soria are trademarks of the K-Industires group of companies. This product is for Kevin only.
Home
First Comic
Latest Comic
Archive
Latest Comic:


Instructions: Click on the radio buttons as they are selected randomly by the computer. 1 point per hit, minus 1 point per miss.
Instructions:


- A trustworthy community.
- Trying to increase the count of honest people is our society.(They are kinda rare na?)
- Trying to minimise your loss in college years because college is only for happy-fun memories.
- Interaction with people who you would’ve never interacted with otherwise.
- There’s no communication barrier.
- Accountable people for questioning so that you can trust us without a doubt.


public class RSBNamespaceBuilder
extends java.lang.Object
RSB-specific terminology:
In-slot is Listener
.
Out-slot is Informer
.
In this documentation the generic terminology is used, to be symmetric to
the other NamespaceBuilders.
Scope consists of Namespace and Label. Namespace is the part before the last slash of the Scope and Label is the part after the last slash of the Scope.
For method parameters Scopes are handled without leading and trailing slashes (they will be added automatically when the RSBNamespaceBuilder interacts with the RSB network).
| Modifier and Type | Method and Description |
|---|---|
static AbstractSlotListener |
getMasterInSlotListener() |
static java.util.HashMap<java.lang.Class<?>,ClassMatcher> |
getMatchProtobufToOtherMap()
Gets the map of matching between protobuf classes and other classes.
|
static java.lang.String |
getXioCodesFilename()
Returns the name of the file with XIO code mapping.
|
static void |
initializeInSlots()
Initializes inslots in dynamic mode.
|
static void |
initializeInSlots(java.util.ArrayList<AbstractSlot> predefinedSlots)
Creates in-slots and takes care of setting them up.
|
static void |
initializeOutSlot()
Initializes dynamic out-slot creation.
|
static void |
initializeOutSlot(java.util.ArrayList<AbstractSlot> predefinedSlots)
Creates out-slots (='informer') and takes care of setting them up.
|
static void |
initializeProtobuf()
Initializes protobuf classes.
|
static void |
removeAll()
Remove all slots.
|
static void |
setMasterInSlotListener(AbstractSlotListener inSlotListener)
Here the application can register its listener to receive incoming data.
|
static void |
setMatchFile(java.lang.String dir)
Sets the name of a XML file with class-to-class matching
definitions.
|
static void |
setPrefix(java.lang.String prfx)
Sets a prefix for all namespaces for all slots created by this
NamespaceBuilder.
|
static void |
setProtobufDir(java.lang.String dir)
Sets the path to the protobuf folder.
|
static void |
setXioCodesFilename(java.lang.String filename)
Set the name of a XML file with XIO code mapping.
|
static boolean |
write(java.lang.String scope,
java.lang.Object data)
Sends given data to given outslot (='informer').
|
static boolean |
write(java.lang.String label,
java.lang.Object data,
java.lang.String namespace)
Sends data to the outslot with the given label and namespace.
|
public static void initializeInSlots(java.util.ArrayList<AbstractSlot> predefinedSlots)
AbstractSlot
s is given, only those in-slots are created. If the
array is null
(or if the overloaded version without
parameters is used), a in-slot is created that listens to the top most
namespace (so, only prefix).predefinedSlots
- an ArrayList with predefined in-slots, or
null
if not neededpublic static void initializeInSlots()
null
for the parameter.public static void initializeOutSlot(java.util.ArrayList<AbstractSlot> predefinedSlots)
AbstractSlot
s is given, only those out-slots are
created. If the array is null
(or if the overloaded
version without parameters is used), out-slots are created dynamically
on demand.
If using predefined out-slots, all data that is written to an unknown out-slot will be ignored.
If class matching pairs are given, out-slots will be created for the matching class (otherwise for the given type of the abstract slot).
predefinedSlots
- an ArrayList with predefined in-slots, or
null
if not neededpublic static void initializeOutSlot()
initializeOutSlots(null)
.
See overloaded methods for more details.public static void initializeProtobuf()
public static void removeAll()
public static boolean write(java.lang.String label, java.lang.Object data, java.lang.String namespace)
The concatenation of the Namespace a slash and the Label gives the Scope.
Example:
Namespace 'Venice/test'
and Label 'slotA'
gives the scope 'Venice/test/slotA'
.
label
- Label of the outslot (w/o leading or trailing slash)data
- the data to be send (class should match the datatype of the
outslot.namespace
- Namespace of the outslot (w/o leading or trailing slash)true
if the data was send without problems,
otherwise false
public static boolean write(java.lang.String scope, java.lang.Object data)
A Scope consists of a Namespace and a Label. The part before the last slash is the Namespace and the part after the last slash is the Label.
Example:
The scope 'Venice/test/slotA'
consists of the Namespace
'Venice/test'
and the Label 'slotA'
.
scope
- the scope of the outslot (='informer'), w/o leading or trailing slashdata
- the data to be send (class should match the datatype of the
out-slot.true
if the data was send without problems,
otherwise false
public static void setMasterInSlotListener(AbstractSlotListener inSlotListener)
inSlotListener
- A listener object, which will receive incoming data.public static AbstractSlotListener getMasterInSlotListener()
public static void setPrefix(java.lang.String prfx)
prfx
- public static void setProtobufDir(java.lang.String dir)
dir
- A path to the protobuf folder.public static void setMatchFile(java.lang.String dir)
dir
- Filename (can include path)public static java.util.HashMap<java.lang.Class<?>,ClassMatcher> getMatchProtobufToOtherMap()
public static void setXioCodesFilename(java.lang.String filename)
filename
- A filename (can include path)public static java.lang.String getXioCodesFilename()


CSE Labs Resources
Lab resources to be checked
Semester I
Subject 1.1
Subject 1.2
Subject 1.3
Semester II
Subject 2.1
Subject 2.2
Subject 2.3
Semester III
Subject 3.1
Subject 3.2
Subject 3.3
Semester IV
Subject 4.1
Subject 4.2
Subject 4.3
Semester V
Subject 5.1
Subject 5.2
Subject 5.3
Semester VI
Subject 6.1
Subject 6.2
Subject 6.3
Semester VII
Subject 7.1
Subject 7.2
Subject 7.3
Semester VIII
Subject 8.1
Subject 8.2
Subject 8.3
Semester VIII
Subject 8.1
Subject 8.2
Subject 8.3


Account: (defaults to Brightcove sample account)
Client id: (defaults to Brightcove sample account)
Client secret: (defaults to Brightcove sample account)
Ingest profile: or Custom Profile: (you must use the name exactly as it appears in the Video Cloud system, or the request will fail)
Video name: (if left blank, file name will be used)
Video source file URL: (if left blank, a sample video will be used)
Start date: (default: now)
End: (default: never)
Full request body for the CMS API call:
Request data will appear here....
Full request body for the DI API call:
Start Ingest
Response will appear here...


Did anyone buy the smaller Pixel 4?
Source: Daniel Bader / Android Central
Every year since 2016, Google launches two versions of its flagship Pixel phone — a regular Pixel and larger, more expensive Pixel XL. This year, we got the Pixel 4 and Pixel 4 XL.
These latest Pixel phones have come under fire for poor battery life, especially the smaller Pixel 4 and its measly 2,800 mAh unit. It struggles to get through just one day of normal use, and as such, has a lot of people recommending the bigger Pixel 4 XL over it.
With that being the case, it's a bit surprising to look through the AC forums and see how many people opted for the Pixel 4.
henryfool3 11-09-2019 07:28 PM I've got the 4. switched from the Samsung s10e. so far I'm very happy with my decision. size is great. phone is fast and snappy. face unlock is fantastic and fast. I'm way happier using that than the fingerprint, but that's my preference. battery wise I'm ok so far. I'm always around a charger if I need. but frankly, for my usage, I don't see a real difference between the s10e and the 4 in... Reply
mwboost 11-11-2019 04:46 AM I have the 4. Battery is slightly better than my 3 was. I haven't checked usage but I can notice a difference. It's a good size, overall similar to the 3. Good size for a smaller phone.Slightly bigger screen than the 3 was. Lose more around the edges when zooming YouTube videos now though. Display is definitely warmer than my 3. (I prefer the 3's cooler display). Still nice, clean and sharp. ... Reply
merlin29 11-11-2019 04:14 PM I have the Pixel 4 64GB white one and after a week the battery is better it’s adapting to my use and I have set up the Pixel with digital wellbeing and motion sense off as l do not need them, and with minimum apps required, the assistant is excellent compared to my old I phone Siri, it’s a compact and well built phone looks good too and with November security up date, I have no complaints it... Reply
KrisYYC 11-12-2019 11:42 AM I'm using the smaller Pixel 4 and it's perfect for my usage. I'm getting slightly better battery life than my Pixel 3 and that's with 90hz forced on etc. But I'm not into mobile gaming or video streaming etc. Majority of my use is messaging/calls, web browsing and some music playback of songs stored on the device itself. YMMV Reply
What about you? Did you buy the smaller Pixel 4?
Join the conversation in the forums!
Get More Pixel 4
Google Pixel 4 & 4 XL
- Google Pixel 4 review
- Google Pixel 4 XL review
- Best Pixel 4 cases
- Best Pixel 4 screen protectors
- Best Pixel 4 XL cases
- Best Pixel 4 XL screen protectors
We may earn a commission for purchases using our links. Learn more.


--- title: about layout: default bodyClass: page-team-list ---
Munnick vision was Founded in July of 2018
After having been in the Information Technology industry for over 14 years, 3 of those years were worked at one of the best investment banks in the world Rand Merchant Bank as a desktop technician and 10+ years were spent working for the technology giant that is Apple Mac as a senior technical consultant.
During her 14-year run in the industry a huge amount of experience was gained and Munnick Visions was born as a result of the mistakes that I learned big organizations make as well as a huge gap in the market that was not at all catering to the public but are more based on business to business relationships and are focused on catering to large corporations and over looking Small businesses, start ups as well as the average consumer.
Munnick Visions is 100% Black female owned and was established out of pure passion for the information technology industry as well as years of experience.
Our aim at Munnick Visions is to provide exceptional IT service as well as also provide our clients with a start to finish package IE: the sale of hardware consisting of Laptops, Desktops, Mice Keyboards as well as full office set up and Full IT after services


halt()
Immediately ends an animation run.
Animations will typically run until you halt them manually using the
keyboard shortcut. The halt() command lets you "bail out" of an animation from code. This can be quite useful during debugging, but we discourage using it in scripts that you share with others.def draw(): if FRAME==100: halt()


--- layout: page title: About header-img: "img/about-bg.png" ---
This page serves as my blog for my experience at Flatiron School/


| First Name | {{user.first_name}} |
|---|---|
| Last Name | {{user.last_name}} |
| {{user.email}} | |
| Phone | {{user.phone}} |
| Address1 | {{address.street1}} |
|---|---|
| Address2 | {{address.street2}} |
| City | {{address.city}} |
| State | {{address.state}} |
| Country | {{address.country}} |
| Zipcode | {{address.zipcode}} |


Before Change
cache_subdir="models")
model.load_weights(weights_path, by_name=True)
elif weights == "cityscapes":
if backbone == "xception":
weights_path = "/home/raul/.keras/models/deeplabv3_xception_tf_dim_ordering_tf_kernels_cityscapes.h5"
model.load_weights(weights_path, by_name=True)
return model
def preprocess_input(x):
After Change
cache_subdir="models")
model.load_weights(weights_path, by_name=True)
elif weights == "cityscapes":
if backbone == "xception":
weights_path = get_file("deeplabv3_xception_tf_dim_ordering_tf_kernels_cityscapes.h5",
WEIGHTS_PATH_X_CS,
cache_subdir="models")
else:
weights_path = get_file("deeplabv3_mobilenetv2_tf_dim_ordering_tf_kernels_cityscapes.h5",
WEIGHTS_PATH_MOBILE_CS,
cache_subdir="models")
model.load_weights(weights_path, by_name=True)
return model


To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video


{% if post %}
The API searches and retrieves live articles from all over the web.
Find the article of your choice by the press of one button.
We are working on producing random article suggestion based on user interest.